Given a 2d grid map of ‘1’s (land) and ‘0’s (water), count 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.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
题意:
计算数组中的‘1’块的个数。
思路:
记忆化DFS。
终止条件:
- 数组越界
- 已被访问过
- 元素值不为‘1’
解法1:12ms
int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};
class Solution {
public:
int count = 0;
int numIslands(vector<vector<char> >& grid) {
if (!grid.size()) return 0;
int n = grid.size();
int m = grid[0].size();
vector<vector<int> > visited(n, vector<int>(m, 0));
for(int i = 0;i < n;++i){
for(int j = 0;j < m;++j){
if (grid[i][j] == '1' && !visited[i][j]){//1、学习记录DFS执行次数的方法。执行前加个判断,使得执行的DFS必定可行。
dfs(i,j,grid,visited);
count++;
}
}
}
return count;
}
void dfs(int i,int j,vector<vector<char> >& grid,vector<vector<int> >& visited){
int n = grid.size();
int m = grid[0].size();
if(i<0||i>=n||j<0||j>=m||visited[i][j]||grid[i][j]=='0') return;
visited[i][j] = 1;
for(int k=0;k<4;++k){
int nx = i + dx[k];
int ny = j + dy[k];
dfs(nx,ny,grid,visited);
}
return;
}
};
上面程序的执行时间是12ms,这里还有一个8ms的解法,核心思想和解法1相同,区别只在于没有使用visited来记录元素是否访问过,而是用grid自身来记录,访问过的元素都修改为’w’。这样做既节省了空间,又节省了访问和判断visited的时间。
解法2:8ms
int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};
class Solution {
public:
int count = 0;
int numIslands(vector<vector<char> >& grid) {
if (!grid.size()) return 0;
int n = grid.size();
int m = grid[0].size();
for(int i = 0;i < n;++i){
for(int j = 0;j < m;++j){
if(grid[i][j]=='1'){
dfs(i,j,n,m,grid);
count++;
}
}
}
return count;
}
void dfs(int i,int j,int n,int m,vector<vector<char> >& grid){
if(i<0||i>=n||j<0||j>=m||grid[i][j]=='0'||grid[i][j]=='w') return;
grid[i][j] = 'w';
for(int k=0;k<4;++k){
int nx = i + dx[k];
int ny = j + dy[k];
dfs(nx,ny,n,m,grid);
}
return;
}
};
C++知识点:
类的成员变量、全局变量的访问权限