Walls and Gates
Fill each empty room with distance to nearest gate and return updated grid
Given a non-empty rectangular integer grid rooms, where -1 denotes a wall, 0 a gate, and 2147483647 an empty room, return the updated grid with each empty room replaced by its shortest distance to any gate. Distance counts horizontal or vertical steps through non-wall cells; diagonal moves are not allowed. Leave walls and gates unchanged, and leave an empty room at 2147483647 if no gate is reachable.
Examples
You write
walls_and_gates(rooms: List[List[int]])
Example 1
- Input
- rooms = [[INF,-1,0,INF],[INF,INF,INF,-1],[INF,-1,INF,-1],[0,-1,INF,INF]]
- returns
- [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
Example 2
- Input
- rooms = [[-1]]
- returns
- [[-1]]
The pattern behind it
Arrays & Hashing
I reach for it when
- You catch yourself scanning the array again for every element.
- The problem asks about duplicates, pairs, counts or groups.
Say this before you type. Say what the key is and what the value remembers, before you write the loop.
All 127 Arrays & Hashing problemsGraphs
I reach for it when
- The input is edges, prerequisites or connections.
- You need cycles, an ordering or connected groups.
Say this before you type. Say whether the edges are directed, and which of the three jobs you are doing.
All 32 Graphs problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Prep guides that list this problem
Our company tags come from public interview write-ups. None of these is a confirmed question.