leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

1254.cpp (1204B)


      1 class Solution {
      2     int n, m;
      3     bool valid(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; }
      4 
      5     void flood_fill(vector<vector<int>> &grid, int x, int y) {
      6         grid[x][y] = 1;
      7         if (valid(x + 1, y) && !grid[x + 1][y]) flood_fill(grid, x + 1, y);
      8         if (valid(x - 1, y) && !grid[x - 1][y]) flood_fill(grid, x - 1, y);
      9         if (valid(x, y + 1) && !grid[x][y + 1]) flood_fill(grid, x, y + 1);
     10         if (valid(x, y - 1) && !grid[x][y - 1]) flood_fill(grid, x, y - 1);
     11     }
     12 
     13   public:
     14     int closedIsland(vector<vector<int>> &grid) {
     15         n = grid.size(), m = grid[0].size();
     16         for (int i = 0; i < n; i++) {
     17             if (!grid[i][0]) flood_fill(grid, i, 0);
     18             if (!grid[i][m - 1]) flood_fill(grid, i, m - 1);
     19         }
     20         for (int i = 0; i < m; i++) {
     21             if (!grid[0][i]) flood_fill(grid, 0, i);
     22             if (!grid[n - 1][i]) flood_fill(grid, n - 1, i);
     23         }
     24 
     25         int res = 0;
     26         for (int i = 1; i < n - 1; i++) {
     27             for (int j = 1; j < m - 1; j++) {
     28                 if (grid[i][j]) continue;
     29                 flood_fill(grid, i, j);
     30                 res++;
     31             }
     32         }
     33 
     34         return res;
     35     }
     36 };