Leetcode 200 Number of Islands
题意
给定一个二维矩阵,只含有0和1,1连接成片构成岛屿。求有多少个这样的岛屿
题目链接
https://leetcode.com/problems/number-of-islands/description/
思路
遍历二维矩阵,从遍历到之前没有visit到的1开始dfs, dfs是用来mark 已经遍历到的点为visited过。 并且每次遇到没有visit过的1时计数。
题解
class Solution {
public:
int m;
int n;
int numIslands(vector<vector<char>>& grid) {
int res = 0;
m = grid.size();
n = grid[0].size();
vector<vector<bool>> vis(m,vector<bool>(n,false));
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == '1' && !vis[i][j]) {
dfs(grid, vis, i, j);
res += 1;
}
}
}
return res;
}
void dfs(vector<vector<char>>& grid, vector<vector<bool>>& vis,int x, int y) {
vis[x][y] = true;
int dk[] = {-1, 0, 1, 0, -1};
for(int i = 0; i < 4; i++) {
int nx = x + dk[i];
int ny = y + dk[i+1];
if(nx >= 0 && nx < m && ny >= 0 && ny < n && !vis[nx][ny] && grid[x][y] == '1') {
dfs(grid, vis, nx, ny);
}
}
}
};
时间复杂度:
O
(
m
n
)
O(mn)
O(mn) m,n 为二维矩阵的长宽
空间复杂度:
O
(
m
n
)
O(mn)
O(mn) m,n 为二维矩阵的长宽