Maps app~15 min2s · 256 MBtarget O(R × C) time, O(R × C) spaceclassic twin: lc-733dfs
A maps app lets city planners edit a land-use layer. The layer is a grid of map tiles, and each tile holds a land-use code: 2 for parkland, 3 for housing, and so on.
A planner taps one tile and picks a new code. The editor then repaints the tapped tile's whole region: every tile with the same code that connects to it through up, right, down and left steps. Tiles that only touch at a corner are not connected. A layer holds up to 400 by 400 tiles.
Write repaint_region(tiles, row, col, code).
tiles is the grid of codes, a list of rows. tiles[row][col] is the tapped tile.code, and return the grid.code equals the old code, nothing changes.Input: tiles = [[2, 2, 0, 1], [2, 0, 0, 1], [2, 2, 3, 1], [0, 2, 2, 2]], row = 0, col = 0, code = 5
Output: [[5, 5, 0, 1], [5, 0, 0, 1], [5, 5, 3, 1], [0, 5, 5, 5]]The tapped tile (0, 0) has code 2. The fill uses a stack and repaints each tile as it is pushed.
| Step | Popped | Repainted and pushed | Stack after (top last) |
|---|---|---|---|
| start | (0, 0) | (0, 0) | |
| 1 | (0, 0) | (0, 1), (1, 0) | (0, 1), (1, 0) |
| 2 | (1, 0) | (2, 0) | (0, 1), (2, 0) |
| 3 | (2, 0) | (2, 1) | (0, 1), (2, 1) |
| 4 | (2, 1) | (3, 1) | (0, 1), (3, 1) |
| 5 | (3, 1) | (3, 2) | (0, 1), (3, 2) |
| 6 | (3, 2) | (3, 3) | (0, 1), (3, 3) |
| 7, 8 | (3, 3), then (0, 1) | none | empty |
Eight tiles change. The code 2 at (3, 3) joins through (3, 2), even though it is far from the tap.
Input: tiles = [[4, 4], [4, 0]], row = 0, col = 0, code = 4
Output: [[4, 4], [4, 0]]The new code is the old code, so the map stays as it is.
Input: tiles = [[1, 0], [0, 1]], row = 0, col = 0, code = 7
Output: [[7, 0], [0, 1]]The two tiles with code 1 touch only at a corner, so they are separate regions.
1 ≤ rows, columns ≤ 400, and every row has the same length0 ≤ tiles[r][c] ≤ 1000 and 0 ≤ code ≤ 10000 ≤ row < rows and 0 ≤ col < columnsHere the size is the number of tiles: up to 400 × 400 = 160,000. Visiting each tile once and checking its four neighbours is about 640,000 steps, far inside the time limit.
A plan that sweeps the whole map again and again until nothing changes can need one sweep for every tile of a winding region. That is about 160,000 sweeps of 160,000 tiles: far too slow. So each tile should be handled once.