class Solution {
public:
int ans = 0, H, W;
void dfs(int y, int x, vector<vector<int>>& grid, vector<vector<bool>>& visited) {
if(y < 0 || y >= H || x < 0 || x >= W || grid[y][x] == 0) {
ans++;
return ;
}
if(visited[y][x]) return ;
visited[y][x] = true;
dfs(y - 1, x, grid, visited);
dfs(y + 1, x, grid, visited);
dfs(y, x - 1, grid, visited);
dfs(y, x + 1, grid, visited);
}
int islandPerimeter(vector<vector<int>>& grid) {
H = grid.size();
W = grid[0].size();
vector<vector<bool> > visited(H, vector<bool>(W, false));
for(int ii = 0; ii < H; ii++) {
for(int jj = 0; jj < W; jj++) {
if(grid[ii][jj] && !visited[ii][jj]) {
dfs(ii, jj, grid, visited);
return ans;
}
}
}
return 0;
}
};
【leetcode 深度优先搜索 C++】463. Island Perimeter
猜你喜欢
转载自blog.csdn.net/m0_37454852/article/details/113873143
今日推荐
周排行