Copy Example 1:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1
Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3
Solution : (BFS and Connected Components)
Copy class Solution
{
public:
void bfs(vector<vector<char>> &grid, int a, int b)
{
int n = grid.size();
int m = grid[0].size();
queue<pair<int, int>> q;
grid[a][b] = '2';
q.push({a, b});
while (!q.empty())
{
int x = q.front().first;
int y = q.front().second;
q.pop();
if (x - 1 >= 0 && grid[x - 1][y] == '1')
{
q.push({x - 1, y});
grid[x - 1][y] = '2';
}
if (x + 1 < n && grid[x + 1][y] == '1')
{
q.push({x + 1, y});
grid[x + 1][y] = '2';
}
if (y - 1 >= 0 && grid[x][y - 1] == '1')
{
q.push({x, y - 1});
grid[x][y - 1] = '2';
}
if (y + 1 < m && grid[x][y + 1] == '1')
{
q.push({x, y + 1});
grid[x][y + 1] = '2';
}
}
return;
}
int numIslands(vector<vector<char>> &grid)
{
int count = 0;
int n = grid.size();
int m = grid[0].size();
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (grid[i][j] == '1')
{
bfs(grid, i, j);
count++;
}
}
}
return count;
}
};