Friday, August 21, 2015

Number of Islands | Leetcode

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:
11110
11010
11000
00000
Answer: 1

Example 2:
11000
11000
00100
00011
Answer: 3

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

---

Solution: Maintain a boolean grid to mark whether each element in the grid has been seen or not. Iterate through each element in the grid. For each grid element that is not yet seen and is a '1', add the island count and mark all reachable '1' elements as seen.
public class Solution {
    private char[][] grid;
    private int len1;
    private int len2;
    private boolean[][] seen;

    public int numIslands(char[][] grid) {
        if (grid.length == 0 || grid[0].length == 0) return 0;
        
        this.grid = grid;
        len1 = grid.length;
        len2 = grid[0].length;
        seen = new boolean[len1][len2];
        
        int count = 0;
        for (int i = 0; i < len1; i++) {
            for (int j = 0; j < len2; j++) {
                if (seen[i][j]) continue;
                if (grid[i][j] == '0') continue;
                count++;
                markIsland(i, j);
            }
        }
        return count;
    }

    private void markIsland(int i, int j) {
        if (seen[i][j]) return;
        seen[i][j] = true;
        if (i >= 1       && grid[i - 1][j] == '1') markIsland(i - 1, j);
        if (i < len1 - 1 && grid[i + 1][j] == '1') markIsland(i + 1, j);
        if (j >= 1       && grid[i][j - 1] == '1') markIsland(i, j - 1);
        if (j < len2 - 1 && grid[i][j + 1] == '1') markIsland(i, j + 1);
    }
}

No comments: