Given a 2d grid map '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.
class Solution {
int m; //rows
int n; //cols
public:
int numIslands(vector<vector<char>>& grid) {
m = grid.size();
if(m == 0) return 0;
n = grid[0].size();
vector<vector<int>> visited (m, vector<int>(n, 0));
int islands = 0;
for(int i =0; i< m; i++) {
for(int j= 0; j< n; j++) {
if(grid[i][j] == '0' || visited[i][j]) continue;
merge0(grid,visited, i, j);
islands++;
}
}
return islands;
}
private:
void merge0(vector<vector<char>>& grid, vector<vector<int>>& visited, int x, int y){
if(x<0 || x>=m) return;
if(y<0 || y>=n) return;
if(grid[x][y] == '0' || visited[x][y]) return;
visited[x][y] = 1;
// DFS 四个扩展点
// using lvaue so paramter x and y cannot not have & operator
merge0(grid, visited, x + 1, y);
merge0(grid, visited, x - 1, y);
merge0(grid, visited, x , y + 1);
merge0(grid, visited, x , y - 1);
}
}
[Code]
class Solution {
int m; //rows
int n; //cols
public:
int numIslands(vector<vector<char>>& grid) {
m = grid.size();
if(m == 0) return 0;
n = grid[0].size();
int islands = 0;
for(int i =0; i< m; i++) {
for(int j= 0; j< n; j++) {
if(grid[i][j] == '0') continue;
merge(grid, i, j);
islands++;
}
}
return islands;
}
private:
void merge(vector<vector<char>>& grid, int x, int y){
if(x<0 || x>=m) return;
if(y<0 || y>=n) return;
if(grid[x][y] == '0') return;
grid[x][y] = '0';
// DFS 四个扩展点
// using lvaue so paramter x and y cannot not have & operator
merge(grid, x + 1, y);
merge(grid, x - 1, y);
merge(grid, x , y + 1);
merge(grid, x , y - 1);
}
void merge2(vector<vector<char>>& grid, int& x, int& y){
if(x<0 || x>=m) return;
if(y<0 || y>=n) return;
if(grid[x][y] == '0') return;
grid[x][y] ='0';
// DFS 四个扩展点
// using rvalue so paramter x and y can have & operator
int up = x+1;
int down = x-1;
int left = y-1;
int right = y+1;
merge(grid, up, y);
merge(grid, down, y);
merge(grid, x , right);
merge(grid, x , left);
}
};