Number of Islands
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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
对每次出现'1'的区域进行计数,同时深度或广度遍历,然后置为'0'。
解法一:非递归dfs
struct Node
{
int x;
int y;
Node(int newx, int newy): x(newx), y(newy) {}
}; class Solution {
public:
int numIslands(vector<vector<char>> &grid) {
int ret = ;
if(grid.empty() || grid[].empty())
return ret;
int m = grid.size();
int n = grid[].size();
for(int i = ; i < m; i ++)
{
for(int j = ; j < n; j ++)
{
if(grid[i][j] == '')
{
dfs(grid, i, j, m, n);
ret ++;
}
}
}
return ret;
} void dfs(vector<vector<char>> &grid, int i, int j, int m, int n)
{
stack<Node*> stk;
Node* rootnode = new Node(i, j);
grid[i][j] = '';
stk.push(rootnode);
while(!stk.empty())
{
Node* top = stk.top();
if(top->x > && grid[top->x-][top->y] == '')
{//check up
grid[top->x-][top->y] = '';
Node* upnode = new Node(top->x-, top->y);
stk.push(upnode);
continue;
}
if(top->x < m- && grid[top->x+][top->y] == '')
{//check down
grid[top->x+][top->y] = '';
Node* downnode = new Node(top->x+, top->y);
stk.push(downnode);
continue;
}
if(top->y > && grid[top->x][top->y-] == '')
{//check left
grid[top->x][top->y-] = '';
Node* leftnode = new Node(top->x, top->y-);
stk.push(leftnode);
continue;
}
if(top->y < n- && grid[top->x][top->y+] == '')
{//check right
grid[top->x][top->y+] = '';
Node* rightnode = new Node(top->x, top->y+);
stk.push(rightnode);
continue;
}
stk.pop();
}
}
};
解法二:递归dfs
class Solution {
public:
int numIslands(vector<vector<char>> &grid) {
int ret = ;
if(grid.empty() || grid[].empty())
return ret;
int m = grid.size();
int n = grid[].size();
for(int i = ; i < m; i ++)
{
for(int j = ; j < n; j ++)
{
if(grid[i][j] == '')
{
dfs(grid, i, j, m, n);
ret ++;
}
}
}
return ret;
} void dfs(vector<vector<char>> &grid, int i, int j, int m, int n)
{
grid[i][j] = '';
if(i > && grid[i-][j] == '')
dfs(grid, i-, j, m, n);
if(i < m- && grid[i+][j] == '')
dfs(grid, i+, j, m, n);
if(j > && grid[i][j-] == '')
dfs(grid, i, j-, m, n);
if(j < n- && grid[i][j+] == '')
dfs(grid, i, j+, m, n);
}
};