Sunday, November 10, 2019

Leetcode 1254. Number of Closed Islands

https://leetcode.com/problems/number-of-closed-islands/description/


Notes:

The question can be viewed as a follow-up of the Number of Islands. For this one, we need to check the neighbors of the most out layer of the island. If one of them is boundary, it is not a closed island.

So we can do this in a BFS naturally, since BFS expands layer-by-layer gradually.

See the code below:

  1. class Solution {
  2. public:
  3.     int closedIsland(vector<vector<int>>& grid) {
  4.         int res = 0;
  5.         int m = grid.size(), n = grid[0].size();
  6.         vector<vector<int>> visit(m, vector<int>(n, 0));//not needed if we can modify grid' values
  7.         for(int i=0; i<m; ++i) {
  8.             for(int j=0; j<n; ++j) {
  9.                 if(grid[i][j] == 0 && !visit[i][j]) {
  10.                     bfs(grid, i, j, visit, res);
  11.                 }
  12.             }
  13.         }
  14.         return res;
  15.     }
  16. private:
  17.     void bfs(vector<vector<int>>& gd, int x, int y, vector<vector<int>>& visit, int &res) {
  18.         queue<pair<int, int>> q;
  19.         q.push({x, y});
  20.         visit[x][y] = 1;
  21.         vector<int> dirs = {-1, 0, 1, 0, -1};
  22.         bool ed = false;//this is the only difference
  23.         while(q.size()) {
  24.             auto t = q.front();
  25.             q.pop();
  26.             for(int i=0; i+1<dirs.size(); ++i) {
  27.                 int a = t.first + dirs[i], b = t.second + dirs[i+1];
  28.                 if(a<0 || a>= gd.size() || b<0 || b>=gd[0].size()) {
  29.                     ed = true;//is edge
  30.                     continue;
  31.                 }
  32.                 if(visit[a][b] || gd[a][b]) continue;
  33.                 q.push({a, b});
  34.                 visit[a][b] = 1;
  35.             }
  36.         }
  37.         if(!ed) ++res;
  38.     }
  39. };

No comments:

Post a Comment