• leetcode1905 统计子岛屿


    思路:

    在grid2中bfs/dfs寻找岛屿的同时判断这个岛屿对应的位置在grid1中是否全部为1。

    实现:

     1 class Solution
     2 {
     3 public:
     4     int dx[4] = {0, 1, 0, -1};
     5     int dy[4] = {1, 0, -1, 0};
     6     bool dfs(int x, int y, vector<vector<int>>& g1, vector<vector<int>>& g2, vector<vector<bool>>& vis)
     7     {
     8         bool res = true;
     9         if (g1[x][y] == 0) res = false; 
    10         vis[x][y] = true;
    11         int n = g2.size(), m = g2[0].size();
    12         for (int i = 0; i < 4; i++)
    13         {
    14             int nx = x + dx[i], ny = y + dy[i];
    15             if (nx >= 0 and nx < n and ny >= 0 and ny < m and g2[nx][ny] == 1 and !vis[nx][ny])
    16             {
    17                 res &= dfs(nx, ny, g1, g2, vis);
    18             }
    19         }
    20         return res;
    21     }
    22     int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2)
    23     {
    24         int n = grid1.size(), m = grid1[0].size();
    25         vector<vector<bool>> vis(n, vector<bool>(m, false));
    26         int res = 0;
    27         for (int i = 0; i < n; i++)
    28         {
    29             for (int j = 0; j < m; j++)
    30             {
    31                 if (grid2[i][j] == 1 and !vis[i][j])
    32                 {
    33                     res += dfs(i, j, grid1, grid2, vis);
    34                 }
    35             }
    36         }
    37         return res;
    38     }
    39 }
  • 相关阅读:
    函数中this指向问题及函数不同方式的调用
    拷贝继承
    组合继承
    借用构造函数
    继承
    UVA-11054(扫描法)
    hihocoder-1347 小h的树上的朋友(lca+线段树)
    UVA-10391(字符串检索)
    UVA-10125(中途相遇法)
    UVA-10827(前缀和降维)
  • 原文地址:https://www.cnblogs.com/wangyiming/p/14920400.html
Copyright © 2020-2023  润新知