显然这是一个用dfs解决的问题,话不多说,放代码吧
class Solution {
public int numIslands(char[][] grid) {
map = grid;
int count = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (map[i][j] == '1') {
//计数
dfs(i, j);
count++;
}
}
}
return count;
}
public static char[][] map;
//遍历四个方向
private final static int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public void dfs(int x, int y) {
map[x][y] = '0';
for (int i = 0; i < 4; i++) {
int newX = x + directions[i][0];
int newY = y + directions[i][1];
//判断条件
if (newX >= 0 && newY >= 0 && newX < map.length && newY < map[0].length && map[newX][newY] == '1') {
dfs(newX, newY);
}
}
return;
}
}