1. BFS with Queue and Visited Matrix
Intuition
Preserves the input grid immutably by maintaining an explicit boolean visited matrix. BFS explores the component layer by layer using a FIFO queue.
Algorithm
- Initialize m x n boolean visited array to false.
- Initialize islandCount = 0.
- Loop r from 0 to m-1 and c from 0 to n-1:
- If grid[r][c] ==
1and !visited[r][c]: - islandCount++.
- Enqueue (r, c) and mark visited[r][c] = true.
- While queue is not empty:
- Pop (currR, currC).
- For 4 directions (dr, dc):
- nr = currR + dr, nc = currC + dc.
- If in bounds, grid[nr][nc] ==
1, and !visited[nr][nc]: - Mark visited[nr][nc] = true, push (nr, nc) into queue.
- Return islandCount.
#include <iostream>#include <vector>#include <queue> class Solution {public: int numIslands(std::vector<std::vector<char>>& grid) { if (grid.empty()) return 0; int m = grid.size(); int n = grid[0].size(); std::vector<std::vector<bool>> visited(m, std::vector<bool>(n, false)); int count = 0; int dr[] = {-1, 1, 0, 0}; int dc[] = {0, 0, -1, 1}; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == '1' && !visited[i][j]) { count++; std::queue<std::pair<int, int>> q; q.push({i, j}); visited[i][j] = true; while (!q.empty()) { auto [r, c] = q.front(); q.pop(); for (int k = 0; k < 4; ++k) { int nr = r + dr[k]; int nc = c + dc[k]; if (nr >= 0 && nr < m && nc >= 0 && nc < n && grid[nr][nc] == '1' && !visited[nr][nc]) { visited[nr][nc] = true; q.push({nr, nc}); } } } } } } return count; }}; int main() { Solution sol; std::vector<std::vector<char>> grid = { {'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'} }; std::cout << "BFS Islands Count: " << sol.numIslands(grid) << " (Expected: 3)\n"; return 0;}Time & Space Complexity
- Time complexity:
O(m * n) - Space complexity:
O(m * n)