[Leetcode] BFS
DFS一般会使用递归调用的方式来实现,简单,但是如果递归的深度非常大,可能会造成递归栈的overflow
BFS可以实现对图的非递归遍历。
在leetcode当中有两道经典的BFS遍历的题目
1 public class Solution { 2 private void set(int r,int c, char[][]grid,int rownum, int colnum,Queue<Integer> queue){ 3 if(r>=0&&r<rownum&&c>=0&&c<colnum&&grid[r][c]=='1'){ 4 grid[r][c]='2'; 5 queue.offer(r * colnum + c); 6 } 7 return; 8 } 9 private boolean expandWater(int r,int c, char[][] grid){ 10 int m= grid.length,n = grid[0].length; 11 if(r<0||r>=m||c<0||c>=n||grid[r][c]!='1') return false; 12 Queue<Integer> queue = new LinkedList<Integer>(); 13 queue.offer(r * n + c); 14 grid[r][c]='2'; 15 while(!queue.isEmpty()){ 16 int dim = queue.poll(); 17 int row = dim / n; 18 int col = dim % n; 19 set(row+1,col,grid,m,n,queue); 20 set(row-1,col,grid,m,n,queue); 21 set(row,col-1,grid,m,n,queue); 22 set(row,col+1,grid,m,n,queue); 23 } 24 return true; 25 } 26 public int numIslands(char[][] grid) { 27 if(grid==null||grid.length==0) return 0; 28 int count =0; 29 for(int i=0;i<grid.length;i++){ 30 for(int j=0;j<grid[0].length;j++){ 31 if(expandWater(i,j,grid)==true) 32 count++; 33 } 34 } 35 for(int i=0;i<grid.length;i++){ 36 for(int j=0;j<grid[0].length;j++){ 37 if(grid[i][j]=='2')grid[i][j]='1'; 38 } 39 } 40 return count; 41 } 42 }
http://www.cnblogs.com/deepblueme/p/4737638.html
1 import java.util.*; 2 3 public class Solution { 4 private void set(int r,int c, Queue<Integer> queue,int rownum, int colnum, char [][] board){ 5 if(r>=0&&r<rownum&&c>=0&&c<colnum&&board[r][c]=='O'){ 6 queue.offer(r * colnum + c); 7 board[r][c]='D'; 8 } 9 } 10 public void BFS(int row,int col, char [][] board){ 11 if(row<0||row>=board.length||col<0||col>=board[0].length||board[row][col]!='O') return; 12 int m= board.length; 13 int n = board[0].length; 14 Queue<Integer> queue = new LinkedList<Integer>(); 15 queue.offer(row*n + col); 16 board[row][col]= 'D'; 17 while(!queue.isEmpty()){ 18 int dimension = queue.poll(); 19 int r = dimension / n; 20 int c = dimension % n; 21 //left 22 set(r,c-1,queue,m,n,board); 23 //up 24 set(r-1,c,queue,m,n,board); 25 //right 26 set(r,c+1,queue,m,n,board); 27 //down 28 set(r+1,c,queue,m,n,board); 29 } 30 } 31 public void solve(char[][] board) { 32 if(board==null|| board.length==0) return; 33 //up down 34 int m = board.length; 35 int n = board[0].length; 36 for(int i=0;i<n;i++){ 37 BFS(0,i,board); 38 BFS(m-1,i,board); 39 } 40 //right left 41 for(int i=1;i<m-1;i++){ 42 BFS(i,0,board); 43 BFS(i,n-1,board); 44 } 45 //flip back D->O,O->X 46 for(int i=0;i<m;i++){ 47 for(int j=0;j<n;j++){ 48 if(board[i][j]=='D') board[i][j] = 'O'; 49 else if(board[i][j]=='O') board[i][j] = 'X'; 50 } 51 } 52 } 53 }