一、题目
Given an m x n 2D binary grid grid which represents a map of ‘1’s (land) and ‘0’s (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Input: grid = [
[“1”,“1”,“1”,“1”,“0”],
[“1”,“1”,“0”,“1”,“0”],
[“1”,“1”,“0”,“0”,“0”],
[“0”,“0”,“0”,“0”,“0”]
]
Output: 1
Example 2:
Input: grid = [
[“1”,“1”,“0”,“0”,“0”],
[“1”,“1”,“0”,“0”,“0”],
[“0”,“0”,“1”,“0”,“0”],
[“0”,“0”,“0”,“1”,“1”]
]
Output: 3
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] is ‘0’ or ‘1’.
二、题解
class Solution {
public:
int dirs[4][2] = {0,1,1,0,-1,0,0,-1};
void dfs(vector<vector<char>>& grid,vector<vector<bool>>& visited,int x,int y){
for(int i = 0;i < 4;i++){
int nextX = x + dirs[i][0];
int nextY = y + dirs[i][1];
if(nextX < 0 || nextX >= grid.size() || nextY < 0 || nextY >= grid[0].size()) continue;
if(!visited[nextX][nextY] && grid[nextX][nextY] == '1'){
visited[nextX][nextY] = true;
dfs(grid,visited,nextX,nextY);
}
}
}
int numIslands(vector<vector<char>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<bool>> visited(m,vector<bool>(n,false));
int res = 0;
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
if(grid[i][j] == '1' && !visited[i][j]){
res++;
visited[i][j] = true;
dfs(grid,visited,i,j);
}
}
}
return res;
}
};
原文地址:https://blog.csdn.net/weixin_46841376/article/details/134721988
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_20770.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!