59. number of islands [어려움]
30 Jul 2020 | Daily Algorithms
- I saw many people post DFS solutions but fewer BFS ones. So I wrote one below. Each time when I see a ‘1’, I increment the counter and then erase all connected ‘1’s using a queue.
BFS methods
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int m = grid.size(); // row
int n = m ? grid[0].size() : 0; // column
int islands = 0;
int offsets[] = {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 + offsets[k];
int c = p.second + offsets[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;
}
};
DFS
- Or I can erase all the connected ‘1’s using 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);
}
};
- I saw many people post DFS solutions but fewer BFS ones. So I wrote one below. Each time when I see a ‘1’, I increment the counter and then erase all connected ‘1’s using a queue.
BFS methods
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int m = grid.size(); // row
int n = m ? grid[0].size() : 0; // column
int islands = 0;
int offsets[] = {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 + offsets[k];
int c = p.second + offsets[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;
}
};
DFS
- Or I can erase all the connected ‘1’s using 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);
}
};
Comments