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.

Example 1:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

 

Solution:   

Traversing the grid.

When we meet ‘1’, Island count plus one. Using DFS to revise all adjacent island to ‘0’.

Continuing to traverse the grid. When we meet the next ‘1’, do the same thing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
    
    int[][] dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    
    public int numIslands(char[][] grid) {
        int nr = grid.length;
        
        if (grid == null || nr == 0) {
            return 0;
        }
        
        int nc = grid[0].length;
        int numIslands = 0;
        
        for (int r = 0; r < nr; r++) {
            for (int c = 0; c < nc; c++) {
                if (grid[r][c] == '1') {
                    numIslands++;
                    dfs(grid, r, c);
                }
            }
        }
        
        return numIslands;
    }
    
    public void dfs(char[][] grid, int r, int c) {
        int nr = grid.length;
        int nc = grid[0].length;
        
        
        if (r < 0 || r > nr - 1 || c < 0 || c > nc - 1 || grid[r][c] != '1') {
            return;
        }
        
        grid[r][c] = '0';
        for (int[] d : dir) {
            dfs(grid, r + d[0], c + d[1]);
        }
    }
}

 

Leave a comment