题意:给一个0,1二维数组,求有多少块“1”(多个1上下左右相连算一块) 思路:DFS/BFS DFS跑了6ms,BFS跑了12ms DFS代码: class Solution { int lenx =0 , leny= 0 ; int [] cx = {1,-1,0,0}, cy = {0,0,1,-1 };
题意:给一个0,1二维数组,求有多少块“1”(多个1上下左右相连算一块)
思路:DFS/BFS
DFS跑了6ms,BFS跑了12ms
DFS代码:
class Solution { int lenx =0 , leny= 0 ; int[] cx = {1,-1,0,0}, cy = {0,0,1,-1}; void dfs(char[][] grid, int tx, int ty){ if(tx <0 || tx >= lenx || ty<0 || ty >= leny) return; if(grid[tx][ty] == ‘0‘) return; grid[tx][ty] = ‘0‘; for(int i=0;i<4;i++) dfs(grid, tx+cx[i], ty+cy[i]); } public int numIslands(char[][] grid) { if(grid.length == 0) return 0; int ans = 0; lenx = grid.length; leny = grid[0].length; for(int i=0;i<lenx;i++){ for(int j=0;j<leny;j++){ if(grid[i][j] == ‘0‘) continue; ans++; dfs(grid,i,j); } } return ans; } }
BFS代码:
class Solution { public int numIslands(char[][] grid) { if(grid.length == 0) return 0; int ans = 0; int lenx = grid.length, leny = grid[0].length; int[] cx = {1,-1,0,0}, cy = {0,0,1,-1}; for(int i=0;i<lenx;i++){ for(int j=0;j<leny;j++){ if(grid[i][j] == ‘0‘) continue; LinkedList<Point> qu = new LinkedList<>(); ans++; qu.add(new Point(i,j)); grid[i][j] = ‘0‘; while(qu.isEmpty() == false){ Point now = qu.remove(); int x = now.x, y = now.y; for(int k=0;k<4;k++){ int tx = x+cx[k], ty = y+cy[k]; if(tx <0 || tx >= lenx || ty<0 || ty >= leny) continue; if(grid[tx][ty] == ‘0‘) continue; grid[tx][ty] = ‘0‘; qu.add(new Point(tx,ty)); } } } } return ans; } }