Number of Islands

This is No.200 in LeetCode.

The solution is below:

public class Solution {

    private int y;
    private int x;

    public int numIslands(char[][] grid) {
        int res = 0;
        y = grid.length;
        if (y == 0) return 0;
        x = grid[0].length;
        for (int i = 0; i < y; i++){
            for (int j = 0; j < x; j++)
                if (grid[i][j] == '1') {
                    DFS(grid, i, j);
                    ++res;
                }
        }    
        return res;
    }

    private void DFS(char[][] grid, int i, int j) {
        if (i < 0 || j < 0 || i >= y || j >= x || grid[i][j] != '1') return;
        grid[i][j] = '0';
        DFS(grid, i + 1, j); // bottom
        DFS(grid, i - 1, j); // top
        DFS(grid, i, j + 1); // right
        DFS(grid, i, j - 1); // left
    }
}

First we got the length of length of the two dimension of array. And then we will use two for loop to traverse the grid, if we got any cell is 1, then we call DFS to search its top, bottom, right and left cell.
During this process, if we got invalid cell, then we just return, otherwise, which means we got a connected cell of 1, then we set it to 0 which means visited, and then check the other near cells.

Leave a Reply