已解决
数据结构:邻接矩阵与邻接表
来自网友在路上 171871提问 提问时间:2023-11-03 18:22:56阅读次数: 71
最佳答案 问答题库718位专家为你答疑解惑
模型图
邻接矩阵
用于反应图中任意两点之间的关联,用二维数组表示比较方便
以行坐标为起点,列坐标为终点如果两个点之间有边,那么标记为绿色,如图:
适合表示稠密矩阵
邻接表
用一维数组 + 链表的形式表示,以数组下标作为起点,链表中的每个节点作为终点形成的邻接表, 如图:
适合表示稀疏矩阵
Java代码实现
邻接矩阵
public class AdjacentMatrix {private static Scanner scanner=new Scanner(System.in); //扫描器public static void main(String[] args) {System.out.println("------图转换为邻接矩阵------");System.out.println("请输入顶点的数量:");int vertex_count= scanner.nextInt();//开辟邻接矩阵boolean[][]adjacentMatrix=new boolean[vertex_count][vertex_count];//初始化矩阵for(int start=0;start<vertex_count;start++){for(int end=0;end<vertex_count;end++){adjacentMatrix[start][end]=false;}}//获取边System.out.println("请输入边的数量:");int edge_count=scanner.nextInt();System.out.println("请输入这些边的起点和终点,如(start end):");for(int i=0;i<edge_count;i++){int start= scanner.nextInt();int end= scanner.nextInt();//填充边adjacentMatrix[start][end]=true;}//打印输入结果System.out.println("所有边如下:");for (int start=0;start<vertex_count;start++){for(int end=0;end<vertex_count;end++){if(adjacentMatrix[start][end]==true)System.out.println(start+"->"+end);}}}
}
测试
//输入:
------图转换为邻接矩阵------
请输入顶点的数量:
4
请输入边的数量:
5
请输入这些边的起点和终点,如(start end):
2 0
2 1
3 0
3 1
0 1//输出:
所有边如下:
0->1
2->0
2->1
3->0
3->1进程已结束,退出代码为 0
邻接表
public class AdjacentList {private static class Edge{public Integer endId;public Edge nextEdge;public Edge(Integer endId) {this.endId = endId;this.nextEdge=null;}public Edge(Integer endId, Edge nextEdge) {this.endId = endId;this.nextEdge = nextEdge;}}private static Scanner scanner=new Scanner(System.in);public static void main(String[] args) {System.out.println("----------图转换为邻接表----------");System.out.println("请输入顶点的数量:");int vertex_count= scanner.nextInt();Edge[]adjacentList=new Edge[vertex_count];System.out.println("请输入边的数量:");int edge_count= scanner.nextInt();System.out.println("请输入这些边:");for(int i=0;i<edge_count;i++){int start= scanner.nextInt();int end= scanner.nextInt();if(adjacentList[start]==null)adjacentList[start]=new Edge(end);elseadjacentList[start].nextEdge=new Edge(end,adjacentList[start].nextEdge);}System.out.println("邻接表如下:");for (int i = 0; i < adjacentList.length; i++){System.out.print("start:"+i+" end:");for(Edge e=adjacentList[i];e!=null;e=e.nextEdge){System.out.print("->"+e.endId);}System.out.println();}}
}
测试
//输入:
----------图转换为邻接表----------
请输入顶点的数量:
4
请输入边的数量:
5
请输入这些边:
2 0
2 1
3 0
3 1
0 1//输出:
邻接表如下:
start:0 end:->1
start:1 end:
start:2 end:->0->1
start:3 end:->0->1进程已结束,退出代码为 0
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"数据结构:邻接矩阵与邻接表":http://eshow365.cn/6-31301-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: 一键报警可视对讲管理机10寸触摸屏管理机
- 下一篇: vue手机项目如何控制蓝牙连接