LeetCode – Number of Islands (Java)

Given a 2-d 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.

Example 1:

11110
11010
11000
00000

Answer: 1

Java Solution 1 – DFS

The basic idea of the following solution is merging adjacent lands, and the merging should be done recursively.

Each element is visited once only. So time is O(m*n).

public int numIslands(char[][] grid) {
    if(grid==null || grid.length==0||grid[0].length==0)
        return 0;
 
    int m = grid.length;
    int n = grid[0].length;
 
    int count=0;
    for(int i=0; i<m; i++){
        for(int j=0; j<n; j++){
            if(grid[i][j]=='1'){
                count++;
                merge(grid, i, j);
            }
        }
    }
 
    return count;
}
 
public void merge(char[][] grid, int i, int j){
    int m=grid.length;
    int n=grid[0].length;
 
    if(i<0||i>=m||j<0||j>=n||grid[i][j]!='1')
        return;
 
    grid[i][j]='X';
 
    merge(grid, i-1, j);
    merge(grid, i+1, j);
    merge(grid, i, j-1);
    merge(grid, i, j+1);
}

Java Solution 2 – Union-Find

Time is O(m*n*log(k)).

public int numIslands(char[][] grid) {
    if(grid==null || grid.length==0 || grid[0].length==0)
        return 0;
 
    int m = grid.length;
    int n = grid[0].length;
 
    int[] dx={-1, 1, 0, 0};
    int[] dy={0, 0, -1, 1};
 
    int[] root = new int[m*n];
 
    int count=0;
    for(int i=0; i<m; i++){
        for(int j=0; j<n; j++){
            if(grid[i][j]=='1'){
                root[i*n+j] = i*n+j;            
                count++;
            }
        }
    }
 
    for(int i=0; i<m; i++){
        for(int j=0; j<n; j++){
            if(grid[i][j]=='1'){
                for(int k=0; k<4; k++){
                    int x = i+dx[k];
                    int y = j+dy[k];
 
                    if(x>=0&&x<m&&y>=0&&y<n&&grid[x][y]=='1'){
                        int cRoot = getRoot(root, i*n+j);
                        int nRoot = getRoot(root, x*n+y);
                        if(nRoot!=cRoot){
                            root[cRoot]=nRoot; //update previous node's root to be current
                            count--;
                        }
 
                    }
                }
            }
        }
    }
 
    return count;
}
 
public int getRoot(int[] arr , int i){
    while(arr[i]!=i){
        i = arr[arr[i]];
    }
 
    return i;
}

Check out Number of Island II.

10 thoughts on “LeetCode – Number of Islands (Java)”

  1. very good approch but I found some bugs in your code, I refactored and this is what I got
    For my input I have 5 islands

    {{1, 1, 0, 0, 0},
    {0, 1, 0, 0, 1},
    {1, 0, 0, 1, 1},
    {0, 0, 0, 0, 0},
    {1, 0, 1, 0, 1}};

    public static int countIslands(int[][] map) {
    if (map == null) {
    throw new IllegalArgumentException("Map cannot be null");
    }

    int islandCount = 0;

    for (int r = 0; r < map.length; r++) // r for rows
    {
    for (int c = 0; c 0 && r<map.length-1 && map[r + 1][c - 1] == 1) || (r<map.length-1 && map[r + 1][c] == 1) || (c < map[0].length-1 && map[r][c + 1] == 1) || (r < map.length-1 && c < map[0].length-1 && map[r + 1][c + 1] == 1)) {
    continue;
    }

    islandCount++;
    }
    }

    return islandCount;
    }

    public static void main(String[] args) {
    int[][] mat = {{1, 1, 0, 0, 0},
    {0, 1, 0, 0, 1},
    {1, 0, 0, 1, 1},
    {0, 0, 0, 0, 0},
    {1, 0, 1, 0, 1}};

    System.out.println(countIslands(mat));
    }

  2. I think I have a much nicer solution on O(m*n) time complexity and O(1) additional space complexity.
    The algorithm is simple:
    Go from top left to bottom right.
    If we’re on a land, check the 2 adjacent tiles, from left and on top.
    If one of them are lands, then this land is part of an already counted island.
    If both are not land, then we discovered a new land – increment.


    int countIslands(int[][] map)
    {
    if (map == null) throw new IllegalArgumentException(“Map cannot be null”);

    int islandCound = 0;

    for (int r = 0 ; r < map.length ; r++) // r for rows
    {
    for (int c = 0 ; c 0 && map[r][c-1] == 1) ||
    (r > 0 && c < map[r-1].length && map[r-1][c] == 1))
    {
    continue;
    }

    islandCound++;
    }
    }

    return islandCound;
    }

  3. int[] dx={-1, 1, 0, 0};
    int[] dy={0, 0, -1, 1};

    why are we having a hard coded array? can someone please explain why this is needed ?

  4. def num_islands():

    visited = set()

    islands = 0

    for i in range(4):

    for j in range(5):

    if m[i][j] == 1:

    visited.add((i,j))

    if i == 0 and j == 0:

    islands += 1

    elif i == 0:

    if m[i][j-1] == 1:

    continue # we have visited this island

    else:

    islands += 1

    else:

    if (i-1,j-1) in visited or

    (i-1,j+1) in visited or

    (i-1,j) in visited or

    (i,j-1) in visited:

    continue

    else:

    islands += 1

    print visited

    return islands

  5. It’s necessary to call merge(gird,i-1,j) and merge(grid,i,j-1).

    e.g
    11111
    00100
    00101 <- this guy cannot be achieved by merge(grid,i+1,j) or merge(grid,i,j+1)
    00111

Leave a Comment