思路
深度优先搜索(一次做出来的!)
public static int numIslands(char[][] grid) {
int ret = 0;
// grid是一个m行n列的矩阵
int m = grid.length;
int n = grid[0].length;
boolean[][] visited = new boolean[m][n];
int[] directions = {-1, 0, 1};
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (grid[i][j] == '1' && !visited[i][j])
{
dfs(grid, i, j, directions, visited);
ret++;
}
return ret;
}
public static void dfs(char[][] grid, int x, int y, int[] directions, boolean[][] visited) {
for (int i : directions)
for (int j : directions)
if (((i+j) == -1 || (i+j) == 1) && validPos(x+i, y+j, grid.length, grid[0].length) && grid[x+i][y+j] == '1' && !visited[x+i][y+j])
{
visited[x+i][y+j] = true;
dfs(grid, x+i, y+j, directions, visited);
}
}
private static boolean validPos(int x, int y, int width, int length)
{
return x >= 0 && x < width && y >= 0 && y < length;
}