题目链接
找1当做起点,并且该起点可以延伸到的1都置位0
public int numIslands(char[][] grid) {
int cnt = 0;
int[][] dir = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1'){
cnt++;
bfs(grid,i,j,dir);
}
}
}
return cnt;
}
public void bfs(char[][] gird ,int sx,int sy,int dir[][]){
Queue<int []> queue = new LinkedList<>();
queue.add(new int[]{sx,sy});
gird[sx][sy] = '0';
while (!queue.isEmpty()){
int cur[] = queue.remove();
int x,y;
for (int i = 0; i < 4; i++) {
x = cur[0] + dir[i][0];
y = cur[1] + dir[i][1];
if (x<0 || x>=gird.length ||y<0 || y>=gird[0].length ||gird[x][y]=='0') continue;
gird[x][y] = '0';
queue.add(new int[]{x,y});
}
}
}