[Leetcode] Number of Islands, Solution (水中的鱼)
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.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
[Thoughts]
1.贪心算法,遍历二维数组,每次只要发现一块land,就BFS其周边,把所有与之连接的land都变成0。BFS完即可island数加一。
2.记得看data type
- lvalue vs rvalue (error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’)
Code: with visited 2D record
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);
}
};