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
- 66 lines of Python from the credited upstream file multi-source-flood-fill.py.
- The implementation visibly relies on sequence storage.
- No explicit 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(object):6 def colorGrid(self, n, m, sources):7 """8 :type n: int9 :type m: int10 :type sources: List[List[int]]11 :rtype: List[List[int]]12 """13 DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))14 result = [[0]*m for _ in xrange(n)]15 q = []16 for r, c, color in sources:17 result[r][c] = color18 q.append((r, c))19 while q:20 new_q = []21 for r, c in q:22 for dr, dc in DIRECTIONS:23 nr, nc = r+dr, c+dc24 if not (0 <= nr < n and 0 <= nc < m):25 continue26 if result[nr][nc] == 0:27 result[nr][nc] = -result[r][c]28 new_q.append((nr, nc))29 elif result[nr][nc] < 0:30 result[nr][nc] = min(result[nr][nc], -result[r][c])31 for nr, nc in new_q:32 result[nr][nc] = -result[nr][nc]33 q = new_q34 return result35 36 37383940class Solution2(object):41 def colorGrid(self, n, m, sources):42 """43 :type n: int44 :type m: int45 :type sources: List[List[int]]46 :rtype: List[List[int]]47 """48 DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))49 sources.sort(key=lambda x: -x[2])50 result = [[0]*m for _ in xrange(n)]51 q = []52 for r, c, color in sources:53 result[r][c] = color54 q.append((r, c))55 while q:56 new_q = []57 for r, c in q:58 for dr, dc in DIRECTIONS:59 nr, nc = r+dr, c+dc60 if not (0 <= nr < n and 0 <= nc < m and result[nr][nc] == 0):61 continue62 result[nr][nc] = result[r][c]63 new_q.append((nr, nc))64 q = new_q65 return result66