Approach
Breadth-first search
For Multi Source Flood Fill, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 77 lines of C++ from the credited upstream file multi-source-flood-fill.cpp.
- The implementation visibly relies on sequence storage.
- 9 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 vector<vector<int>> colorGrid(int n, int m, vector<vector<int>>& sources) {8 static const vector<pair<int, int>>& DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};9 10 vector<vector<int>> result(n, vector<int>(m));11 vector<pair<int, int>> q;12 for (const auto& x : sources) {13 const auto& r = x[0], &c = x[1], &color = x[2];14 result[r][c] = color;15 q.emplace_back(r, c);16 }17 while (!empty(q)) {18 vector<pair<int, int>> new_q;19 for (const auto& [r, c] : q) {20 for (const auto& [dr, dc] : DIRECTIONS) {21 const auto& nr = r + dr, &nc = c + dc;22 if (!(0 <= nr && nr < n && 0 <= nc && nc < m)) {23 continue;24 }25 if (result[nr][nc] == 0) {26 result[nr][nc] = -result[r][c];27 new_q.emplace_back(nr, nc);28 } else if (result[nr][nc] < 0) {29 result[nr][nc] = min(result[nr][nc], -result[r][c]);30 }31 }32 }33 for (const auto& [nr, nc] : new_q) {34 result[nr][nc] = -result[nr][nc];35 }36 q = move(new_q);37 }38 return result;39 }40};41 42434445class Solution2 {46public:47 vector<vector<int>> colorGrid(int n, int m, vector<vector<int>>& sources) {48 static const vector<pair<int, int>>& DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};49 50 ranges::sort(sources, [](const auto& a, const auto& b) {51 return a[2] > b[2];52 });53 vector<vector<int>> result(n, vector<int>(m));54 vector<pair<int, int>> q;55 for (const auto& x : sources) {56 const auto& r = x[0], &c = x[1], &color = x[2];57 result[r][c] = color;58 q.emplace_back(r, c);59 }60 while (!empty(q)) {61 vector<pair<int, int>> new_q;62 for (const auto& [r, c] : q) {63 for (const auto& [dr, dc] : DIRECTIONS) {64 const auto& nr = r + dr, &nc = c + dc;65 if (!(0 <= nr && nr < n && 0 <= nc && nc < m && result[nr][nc] == 0)) {66 continue;67 }68 result[nr][nc] = result[r][c];69 new_q.emplace_back(nr, nc);70 }71 }72 q = move(new_q);73 }74 return result;75 }76};77