1. Iterative BFS with Explicit Queue
Intuition
Starting from (sr, sc), push coordinates into a queue. Dequeue cell by cell, recolor, and enqueue all 4-directional neighbors that match the original color.
Algorithm
- Record originalColor = image[sr][sc].
- If originalColor == color, return image.
- Initialize queue of pairs and push (sr, sc).
- Set image[sr][sc] = color.
- Define directions: [(-1, 0), (1, 0), (0, -1), (0, 1)].
- While queue is not empty:
- Pop (r, c) from queue.
- For each (dr, dc) in directions:
- nr = r + dr, nc = c + dc.
- If 0 <= nr < m and 0 <= nc < n and image[nr][nc] == originalColor:
- image[nr][nc] = color.
- Push (nr, nc) to queue.
- Return image.
#include <iostream>#include <vector>#include <queue> class Solution {public: std::vector<std::vector<int>> floodFill(std::vector<std::vector<int>>& image, int sr, int sc, int color) { int originalColor = image[sr][sc]; if (originalColor == color) return image; int m = image.size(); int n = image[0].size(); std::queue<std::pair<int, int>> q; image[sr][sc] = color; q.push({sr, sc}); int dr[] = {-1, 1, 0, 0}; int dc[] = {0, 0, -1, 1}; while (!q.empty()) { auto [r, c] = q.front(); q.pop(); for (int i = 0; i < 4; ++i) { int nr = r + dr[i]; int nc = c + dc[i]; if (nr >= 0 && nr < m && nc >= 0 && nc < n && image[nr][nc] == originalColor) { image[nr][nc] = color; q.push({nr, nc}); } } } return image; }}; int main() { Solution sol; std::vector<std::vector<int>> image = {{1, 1, 1}, {1, 1, 0}, {1, 0, 1}}; auto res = sol.floodFill(image, 1, 1, 2); std::cout << "BFS Flood Fill result:\n"; for (const auto& row : res) { for (int v : row) std::cout << v << " "; std::cout << "\n"; } return 0;}Time & Space Complexity
- Time complexity:
O(m * n) - Space complexity:
O(m * n)