深度优先遍历和宽度优先遍历深度优先遍历和宽度优先遍历是遍历图中所有顶点的两种方式。 深快速横移(DFS ) cbdpj、深快速横移是找准一条路不断深入的探索方法。 当发现这条路不能通过时,返回前面探索过的节点。 如果前一个节点有未搜索的分支,则继续搜索,如果没有,则返回。 深度优先遍历类似于二叉树中的前序、中序、后序遍历。
深遍历的优先密钥是如何找到搜索到的节点之前的节点,即如何追溯。
可见,深度优先算法的图像图在线显示是搜索顺序,深度优先遍历是回头寻找另一出口的遍历方式。
广度优先遍历(BFS )广度优先遍历是首先搜索起点相邻的几个点,然后搜索距离起点稍远(一层楼)的点,然后搜索距离起点更远(两层楼)的点……这样的一个阶段这类似于二叉树的层序遍历。
宽度优先算法的图像如图所示,宽度优先扫描是按层次向外搜索的,所以为了找到下一个层次的点,需要记录上一个层次搜索了哪个点。
实现原理深度优先算法根据深度优先算法的特性,可以使用栈先进先出的特性来实现。
将搜索到的点存储在堆栈中,遇到困难时将堆栈顶部要素返回到前面的要素,实现回溯
宽度优先算法由于宽度优先算法需要依次回顾迄今为止走过的顶点顺序的特性,可以使用队列先入先出来实现。
首先是第一点1入队1出队,2,3,4,5入队3358www.Sina.com/出队
引用例题参考200个岛屿的数量问题
举出由“1”(陆地)和“0”(水)构成的二维网眼。 请计算网眼中的岛的数量。
岛总是被水包围着,每个岛只能由水平和/或垂直相邻的陆地连接形成。
另外,可以假设网格的四条边都被水包围。
输入: grid=[[“1”、“1”、“1”、“0”]、[“1”、“0”、“1”、“0”]、[“1”、”
publicstaticvoiddfs (char [ ] [ ]网格id,int r,int c ) { int nr=grid.length; int nc=grid[0].length; if|r0|| c0|| r=NR|| c=NC|| grid [ r ] [ c ]='0' ) { return; } grid[r][c]='0'; DFS (网格、r - 1、c ); DFS (网格、r 1、c ); DFS (网格、r、c - 1 ); DFS (网格、r、c 1); } publicstaticintnumislands (char [ ] [ ] grid ) ) if(grid==null||grid.Length==0) { return 0; (} int nr=grid.length; int nc=grid[0].length; int num_islands=0; for(intr=0; r nr; r ) for(intc=0; 数控; c ) if(grid[r][c]=='1' ) { num_islands; DFS (网格、r、c ); } } } return num_islands; }广度优先算法的实现
publicintnumislands (char [ ] [ ] grid ) if ) grid==null||grid.Length==0) { return 0; (} int nr=grid.length; int nc=grid[0].length; int num_islands=0; for(intr=0; r nr; r ) for(intc=0; 数控; c ) if(grid[r][c]=='1' ) { num_islands; grid[r][c]='0'; queueintegerneighbors=new linked list (; neighbors.add(r*NCc ); while (! neighbors.isEmpty () { int id=neighbors.remove; int row=id/nc; int col=id % nc; if (原始-1=0grid [原始-1] [ col ]='1' ) neighbors.add ) (原始-1) * nc col ); 网格[ row-1 ] [ col ]='0'; }if(row1NRgrid[row1][col]='1' ) neighbors.add((row1) * nc col ); 网格[ row1] [ col ]='0'; }if(col-1=0grid[row][col-1]='1' ) neighbors.add(row*NCcol-1 ); 网格[ row ] [ col-1 ]='0'; } if (col1NC网格[ row ] [ col1]=='1' ) neighbors.add(row*NCcol1); 网格[ row ] [ col1]='0'; } } } } } return num_islands; }