Number of Islands

☆☆☆☆☆

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.


static int[] di = {-1, 0, 0, 1};
static int[] dj = {0, 1, -1, 0};
public int numIslands(char[][] grid) {
    if (grid == null || grid.length==0) return 0;
    int count = 0;
    for (int i = 0; i < grid.length; ++i) {
        for (int j = 0; j < grid[0].length; ++j) {
            if (grid[i][j] == '1') {
                dfsMarkUp(grid, i, j);
                count++;
            }
        }
    }
    return count;
}
public void dfsMarkUp(char[][] grid, int i, int j) {
    grid[i][j] = 'x';
    for (int d = 0; d < di.length; ++d) {
        int x = i + di[d];
        int y = j + dj[d];
        if (0 <= x && x < grid.length && 0 <= y && y < grid[0].length && grid[x][y] == '1')
            dfsMarkUp(grid, i + di[d], j + dj[d]);
    }
}

results matching ""

    No results matching ""