200. Number of Islands
Description:
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.
Difficulty:Medium
Example:
Input:
11110
11010
11000
00000
Output: 1
方法:深度搜索,改变原值
- Time complexity : O ( m ∗ n ) O\left (m*n \right ) O(m∗n)
- Space complexity :
O
(
m
∗
n
)
O\left (m*n \right )
O(m∗n)
思路:
枚举元素,遇到‘1’结果加一,然后将此元素变成‘0’,深搜其上下左右并将上下左右的‘1’变成‘0’,递归。
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if(grid.size()==0 || grid[0].size()==0) return 0;
int res = 0;
for(int i = 0; i < grid.size(); i++){
for(int j = 0; j < grid[0].size(); j++){
if(grid[i][j] == '1'){
res++;
DSF(grid, i, j);
}
}
}
return res;
}
void DSF(vector<vector<char>> &grid, int i, int j){
grid[i][j] = '0';
if (i > 0 && grid[i-1][j] == '1')
DSF(grid, i-1, j);
if (i < grid.size()-1 && grid[i+1][j] == '1')
DSF(grid, i+1, j);
if (j > 0 && grid[i][j-1] == '1')
DSF(grid, i, j-1);
if (j < grid[0].size()-1 && grid[i][j+1] == '1')
DSF(grid, i, j+1);
}
};