题解 | #岛屿数量#
岛屿数量
http://www.nowcoder.com/practice/0c9664d1554e466aa107d899418e814e
public int solve (char[][] grid) { // write code here int count=0; //返回结果 for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[i].length;j++){ //从第一个开始判断,如果是1进行dfs并count++ if(grid[i][j]=='1'){ dfs(grid,i,j); count++; } } } return count; } //进行dfs查找 public void dfs(char[][] grid,int i,int j){ //边界限制,以及遇到海洋就终止 if(i<0||i>=grid.length || j<0|| j>=grid[0].length || grid[i][j]=='0') return; //已经探查过的陆地就使之为“海洋”,避免出现 栈溢出 grid[i][j]='0'; //上下左右 dfs(grid,i+1,j); dfs(grid,i-1,j); dfs(grid,i,j+1); dfs(grid,i,j-1); }