200 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:

11110


11010


11000


00000

Answer: 1

Example 2:

11000


11000


00100


00011

Answer: 3

DFS Solution: O(n)

bool isValid(int row, int col, int height, int width, vector<vector<bool>> &explored, vector<vector<char>> &ar)
{
    return (row >= 0 && row < height && col >= 0 && col < width &&
        explored[row][col] == 0 && ar[row][col] == '1');
}

void dfs_cluster(int row, int col, vector<vector<bool>> &explored,
    vector<vector<char>> &ar)
{
    // up
    if (isValid(row - 1, col, ar.size(), ar.at(row).size(), explored, ar)) {
        explored[row - 1][col] = 1;
        dfs_cluster(row - 1, col, explored, ar);
    }
    // down
    if (isValid(row + 1, col, ar.size(), ar.at(row).size(), explored, ar)) {
        explored[row + 1][col] = 1;
        dfs_cluster(row + 1, col, explored, ar);
    }
    // right
    if (isValid(row, col + 1, ar.size(), ar.at(row).size(), explored, ar)) {
        explored[row][col + 1] = 1;
        dfs_cluster(row, col + 1, explored, ar);
    }
    // left
    if (isValid(row, col - 1, ar.size(), ar.at(row).size(), explored, ar)) {
        explored[row][col - 1] = 1;
        dfs_cluster(row, col - 1, explored, ar);
    }
}


int numIslands(vector<vector<char>>& ar)
{
    int num_clusters = 0;
    vector<vector<bool>> explored_ar(ar.size(), vector<bool>(ar.at(0).size()));

    for (int i = 0; i < ar.size(); i++) {
        for (int j = 0; j < ar.at(i).size(); j++) {
            if (isValid(i, j, ar.size(), ar.at(i).size(), explored_ar, ar)) {
                explored_ar[i][j] = 1;
                dfs_cluster(i, j, explored_ar, ar);
                num_clusters++;
            }
        }
    }

    return num_clusters;
}


int main()
{
    vector<vector<char>> grid = {
        {},
    };
    cout << numIslands(grid) << endl;

    grid = {
        { '1','0','1','1','0','1','1' },
    };
    cout << numIslands(grid) << endl;

    grid = {
        { '1','1','0','0','0' },
        { '1','1','0','0','0' },
        { '0','0','1','0','0' },
        { '0','0','0','1','1' },
    };
    cout << numIslands(grid) << endl;
}

Last updated