leetcode 1020 飞地的数量

简介: leetcode 1020 飞地的数量

飞地的数量

b90ce9ff59cb4bf6ae62bd9079a376d3.png

class Solution {
public:
    int result = 0 , tmp_size = 1;
    int m =0 ,n=0;
    bool borad_flag = false;
    int dir[4][2] = {0,1, 0,-1 , -1,0 , 1,0};
    void dfs(vector<vector<int>>& grid , vector<vector<bool>> &path , int x , int y)
    {
        for(int i=0 ; i<4 ;i++)
        {
            int next_x = x + dir[i][0];
            int next_y = y + dir[i][1];
            if(next_x<0||next_x>=m||next_y<0||next_y>=n)
            {
                borad_flag = true;
                continue;
            }
            if( path[next_x][next_y] == false && grid[next_x][next_y] == 1) 
            {   
                tmp_size++;
                path[next_x][next_y] = true;
                dfs(grid,path,next_x,next_y);
            }
        }
        return;
    }
    int numEnclaves(vector<vector<int>>& grid) {
        m = grid.size();
        n = grid[0].size();
        vector<vector<bool>> path( m , vector<bool>( n ,false) );
        for(int i=0 ; i<m ;i++)
        {
            for(int j=0 ; j<n ;j++)
            {
                if(path[i][j] == false && grid[i][j] == 1)
                {
                    tmp_size = 1;
                    borad_flag = false;
                    path[i][j] = true;
                    dfs(grid,path,i,j);
                    if(borad_flag == false ) result += tmp_size;
                }
            }
        }
        return result;
    }
};


相关文章
LeetCode-1020 飞地的数量
LeetCode-1020 飞地的数量
|
6天前
leetcode-1020:飞地的数量
leetcode-1020:飞地的数量
19 0
|
6天前
|
Go
golang力扣leetcode 1020.飞地的数量
golang力扣leetcode 1020.飞地的数量
11 0
|
人工智能 C++
【LeetCode1020】飞地的数量
从4条边界进行遍历,即遇到边界上的1就递归遍历,把边界上的都为1的连通分量改成数字2,dfs搞完后,就遍历一遍二维数组,剩下的1即所求的飞地数量。
93 0
【LeetCode1020】飞地的数量
|
6天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
9 0
|
6天前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
13 0
|
6天前
|
算法
【刷题】 leetcode 面试题 08.05.递归乘法
递归算法是一种在计算机科学和数学中广泛应用的解决问题的方法,其基本思想是利用问题的自我相似性,即将一个大问题分解为一个或多个相同或相似的小问题来解决。递归算法的核心在于函数(或过程)能够直接或间接地调用自身来求解问题的不同部分,直到达到基本情况(也称为基础案例或终止条件),这时可以直接得出答案而不必再进行递归调用。
25 4
【刷题】 leetcode 面试题 08.05.递归乘法
|
6天前
|
存储 算法 安全
【刷题】 leetcode 面试题 01.06 字符串压缩
来看效果: 非常好!!!过啦!!!
27 5
【刷题】 leetcode 面试题 01.06 字符串压缩
|
6天前
|
存储 算法 测试技术