Open zwkcoding opened 5 years ago
Problem: Nums of Islands Solution ;
another solution uses Union-Find By the way, just counts the numbers , no need to know which grid belongs to which islands, see this compact solution: https://leetcode.com/explore/learn/card/queue-stack/232/practical-application-stack/1380/discuss/56589/C++-BFSDFS. If you need to know attribution relationship for every grid. you could use
HandCoding Code :)
# Solution use BFS
class Solution {
public:
int numIslands(vector<vector<char> >& grid) {
int m = grid.size();
int n = m ? grid[0].size() : 0;
islands = 0;
offset[] = {0, 1, 0, -1, 0};
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == '1') {
islands++;
grid[i][j] = '0';
queue<pair<int, int> > todo;
todo.push({i,j});
while(!todo.empty()) {
pair<int, int> p = todo.front();
todo.pop();
for (int k = 0; k < 4; k++) {
int r = p.first + offset[k],;
int c = p.second + offset[k+1];
if(r >= 0 && r < m && c >= 0 && c < n && grid[r][c] == '1') {
grid[r][c] = '0';
todo.push({r,c});
}
}
}
}
}
}
return islands;
}
};
# Solution uses DFS
class Solution {
public:
int numIslands(vector<vector<char> >& grid) {
int m = grid.size(), n = m ? grid[0].size() : 0, islands = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
islands++;
eraseIslands(grid, i, j);
}
}
}
return islands;
}
private:
void eraseIslands(vector<vector<char> >& grid, int i, int j) {
int m = grid.size(), n = grid[0].size();
if (i < 0 || i == m || j < 0 || j == n || grid[i][j] == '0') {
return;
}
grid[i][j] = '0';
eraseIslands(grid, i - 1, j);
eraseIslands(grid, i + 1, j);
eraseIslands(grid, i, j - 1);
eraseIslands(grid, i, j + 1);
}
};
Keywords: DFS, Recursion Notes:
BFS: processing order conforms adding order, SO FIFO, AND SO
queen
DFS: processing order opposing adding order, SO LIFO, AND SOstack
Above templete uses the implicit stack provided by the Call Stack