200. Number of Islands | LeetCode Solution

 200. Number of Islands | LeetCode Solution

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return 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: grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
Output: 1

Example 2:

Input: grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
Output: 3

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] is '0' or '1'.


class Solution
{
public:
  int ans = 0;

  void dfs(vector<vector<char>> &v, vector<vector<bool>> &check, int i, int j)
  {
    int dx[4] = {-1, 1, 0, 0};
    int dy[4] = {0, 0, -1, 1};
    for (int k = 0; k < 4; k++)
    {
      int currx = dx[k] + i;
      int curry = dy[k] + j;
      if (currx >= 0 && currx < v.size() && curry >= 0 && curry < v[0].size() && check[currx][curry] == 0 && v[currx][curry] == '1')
      {
        check[currx][curry] = 1;
        dfs(v, check, currx, curry);
      }
    }
  }

  void helper(vector<vector<char>> &v, vector<vector<bool>> &check)
  {
    for (int i = 0; i < v.size(); i++)
    {
      for (int j = 0; j < v[0].size(); j++)
      {
        if (v[i][j] == '1' && check[i][j] == 0)
        {
          // cout<<i<<"00 "<<j<<endl;
          dfs(v, check, i, j);
          ans++;
        }
      }
    }
  }

  int numIslands(vector<vector<char>> &grid)
  {
    vector<vector<bool>> check(grid.size(), vector<bool>(grid[0].size(), false));
    helper(grid, check);
    return ans;
  }
};

Post a Comment

0 Comments