LeetCode 1020 Number of Enclaves

标签: 岛屿问题 LeetCode 发布于:2022-02-02 17:19:43 编辑于:2022-02-05 16:54:04 浏览量:985

题目分析

https://leetcode.com/problems/number-of-enclaves/

基本上与 https://leetcode.com/problems/number-of-closed-islands 一致,无非是这里统计元素个数而非岛屿个数。

深度优先搜索

class Solution {
public:
    int numEnclaves(vector<vector<int>>& grid) {
        int count = 0;
        for (int i=0; i<grid.size(); i++) {
            for (int j=0; j<grid[0].size(); j++) {
                if (grid[i][j] == 1) {
                    int cnt = 0;
                    if (travelIsland(i, j, grid, cnt)) {
                        count += cnt;
                    }
                }
            }
        }
        return count;
    }
    
    bool travelIsland(int i, int j, vector<vector<int>>& grid, int& count) {
        if (i < 0 || j < 0 || i >= grid.size() || j >= grid[0].size()) return false;
        if (grid[i][j] == 1) {
            grid[i][j] = 2; // mark as visited island
            count += 1;
            bool f1 = travelIsland(i+1, j, grid, count);
            bool f2 = travelIsland(i-1, j, grid, count);
            bool f3 = travelIsland(i, j+1, grid, count);
            bool f4 = travelIsland(i, j-1, grid, count);
            return f1 && f2 && f3 && f4;
        }
        return true;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/