Woodstock Blog

a tech blog for general algorithmic interview questions

[LeetCode 200] Number of Islands

Question

link

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.

Show Tags
Depth-first Search Breadth-first Search

Analysis

At every ‘1’ position, do DFS.

Solution

I post my code below. Note that we do not actually have to have the method “findLand” - we can simply read through the grid and mark all ‘1’s in one run.

You might want to come up with your own code. Mine is just for reference. This is not an very interesting question, I assume.

Code

public class Solution {
    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;

        Pair firstPiece = findLand(grid, m, n);
        while (firstPiece != null) {
            // mark all neighbors, and count increment
            mark(grid, m, n, firstPiece);
            firstPiece = findLand(grid, m, n);
            count++;
        }

        return count;
    }

    void mark(char[][] grid, int m, int n, Pair p) {
        if (p.x < 0 || p.x == m || p.y < 0 || p.y == n) {
            return;
        } else if (grid[p.x][p.y] != '1') {
            return;
        }
        // mark current and then dfs
        grid[p.x][p.y] = '2';
        mark(grid, m, n, new Pair(p.x - 1, p.y));
        mark(grid, m, n, new Pair(p.x + 1, p.y));
        mark(grid, m, n, new Pair(p.x, p.y - 1));
        mark(grid, m, n, new Pair(p.x, p.y + 1));
    }

    Pair findLand(char[][] grid, int m, int n) {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1') {
                    return new Pair(i, j);
                }
            }
        }
        return null;
    }

    class Pair {
        int x;
        int y;

        public Pair(int a, int b) {
            x = a;
            y = b;
        }
    }
}