图的遍历
来源:互联网 发布:linux查看ftp用户权限 编辑:程序博客网 时间:2024/06/03 21:34
图
神马是图
简单来说,图就是由一些小圆点(称为顶点)和连接这些小圆点的直线(称为边)组成。
对于一个图,我们最常见的需要就是遍历一个图,通过这些边到达每一个顶点。通常我们有两种方式去遍历所有的顶点,一种是深度优先遍历,另一种是广度优先遍历。(对于深度与广度可以参考之前的文章)。
图的表示方法
在计算机语言中我们通常可以通过一个二维数组表示一个图。如同下图:
图中的1表示有边可以联通两个顶点,∞表示没有边联通,0表是自己到自己。这种存储图的方式称为图的邻接矩阵存储法。
图的深度优先遍历
public static Scanner scanner;public static int chart[][]=new int[5][5];public static boolean book[][]=new boolean[5][5];public static int sum=0;public static void dfs(int step){ sum++; if(sum==chart.length){ return; } //当遍历完成后结束遍历 System.out.print(step+"\t"); for(int i=0;i<chart.length;i++ ){ if(chart[step][i]==1&&book[step][i]==false){ book[step][i]=true; dfs(i); } }}//初始化数据@Beforepublic void init(){ scanner=new Scanner(System.in); for(int i=0;i<chart.length;i++){ for(int j=0;j<chart[i].length;j++){ if(i==j){ chart[i][j]=0; } else{ chart[i][j]=Integer.MAX_VALUE; } } } for(int i=0;i<5;i++){ int x=scanner.nextInt(); int y=scanner.nextInt(); chart[x][y]=1; }}@Testpublic void testDfs(){ dfs(0);}
图的广度优先遍历
public static Scanner scanner;public static int chart[][]=new int[5][5];public static boolean book[][]=new boolean[5][5];public static int sum=0;public void bfs(){ Queue<Integer> queue=new LinkedList<Integer>(); queue.offer(0); while(!queue.isEmpty()){ int head=queue.poll(); sum++; System.out.println(head); if(sum==chart.length){ return; } for(int i=0;i<chart.length;i++){ if(chart[head][i]==1&&book[head][i]==false){ book[head][i]=true; queue.offer(i); } } }}@Beforepublic void init(){ scanner=new Scanner(System.in); for(int i=0;i<chart.length;i++){ for(int j=0;j<chart[i].length;j++){ if(i==j){ chart[i][j]=0; } else{ chart[i][j]=Integer.MAX_VALUE; } } } for(int i=0;i<5;i++){ int x=scanner.nextInt(); int y=scanner.nextInt(); chart[x][y]=1; }}@Testpublic void testDfs(){ bfs();}
0 0
- 图:图的遍历(深度优先遍历、广度优先遍历)
- java图的遍历方式(深度遍历、广度遍历)
- java图的遍历方式(深度遍历、广度遍历)
- 图的遍历(深度遍历和广度遍历)
- 图的遍历:深度优先遍历和广度优先遍历
- 图的 深度遍历 广度遍历
- 图的深度遍历和广度遍历
- 图的遍历(深度优先遍历)
- 图的遍历:深度优先遍历
- 图的遍历:宽度优先遍历
- 图的广度遍历和深度遍历
- 图的深度遍历和广度遍历
- 图的遍历-深度优先遍历
- 图的遍历-广度优先遍历
- 图的dfs遍历和bfs遍历
- 图的深度遍历和广度遍历
- 图的遍历算法-马遍历棋盘
- 图的遍历算法-马遍历棋盘
- C++知识点:数组末端下一位置
- join查询要点整合
- Controller的使用
- 大多数的愤怒源于自己的无知——《Excel受保护视图》
- 463. Island Perimeter
- 图的遍历
- SpringBoot非官方教程 | 第八篇:springboot整合mongodb
- Shiro框架学习-身份验证
- Android 动画简单实现
- CF
- 【算法】将一维数组arr中的元素循环左移p个位置
- 数据库特性与隔离级别
- SpringBoot非官方教程 | 第九篇: springboot整合Redis
- 常用的免费英文电子书