【LeetCode】1020. Number of Enclaves(图搜索)
题目
Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)
A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.
Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of moves.
Example 1:
Input: [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation:
There are three 1s that are enclosed by 0s, and one 1 that isn't enclosed because its on the boundary.
Example 2:
Input: [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0
Explanation:
All 1s are either on the boundary or can reach the boundary.
Note:
1 <= A.length <= 500
1 <= A[i].length <= 500
0 <= A[i][j] <= 1
All rows have the same size.
题意
这题大概的意思是:给一个二维的图,其中的 0 表示海洋,1表示陆地。可以从一块陆地向上、下、左、右这4个方向移动,到达另一块陆地。要求返回的是,该图中有多少块陆地,从这些陆地出发是始终无法到达边界的。
思路
其实这题就是 找连通块。
对于一个连通块:
(1)如果其中的所有陆地都不在边界上,则从该连通块中的所有陆地出发,都无法到达边界;
(2)如果其中存在至少1个陆地在边界上,则从该连通块中的任一陆地出发,都可以到达边界;
因此,我们可以先初始化返回的陆地块数为0。然后,采用 dfs 来寻找连通块,如果该块中没有一个陆地在边界上,则返回的陆地块数要加上该连通块中陆地的块数。
代码
class Solution {
public:
map<int, vector<int>>tip;
int ifbound = 0, row, col;
int direction[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int dfs(int i, int j, vector<vector<int>>& A) {
int a, b, c, ans;
tip[i][j] = 1;
if(i == 0 || j == 0 || i == row - 1 || j == col - 1 )
ifbound = 1;
ans = 1;
for(a=0; a<4; ++a) {
b = direction[a][0] + i;
c = direction[a][1] + j;
if(b >=0 && b < row && c >= 0 && c < col && A[b][c] == 1 && tip[b][c] == 0) {
ans += dfs(b, c, A);
}
}
return ans;
}
int numEnclaves(vector<vector<int>>& A) {
int i, j, k, res;
row = A.size();
col = A[0].size();
tip.clear();
vector<int>temp(col);
for(i=0; i<row; ++i)
tip[i] = temp;
res = 0;
for(i=0; i<row; ++i) {
for(j=0; j<col; ++j) {
if(A[i][j] && tip[i][j] == 0) {
ifbound = 0;
k = dfs(i, j, A);
if(ifbound == 0) {
res = res + k;
}
}
}
}
return res;
}
};