Data Structures & Algorithms Graphs — BFS & DFS
💡
Exercise 114

Walls and Gates 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

-1=wall, 0=gate, INF=empty room. Fill each empty room with distance to nearest gate. Multi-source BFS from all gates at once.

Start BFS from all gates (0s). Each level increments distance by 1. Only visit cells still set to INF.

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Fill rooms with shortest distance to a gate. Print each row.
Multi-source BFS: enqueue all gates. For each INF neighbor, set distance = current+1 and enqueue.
🧪 Test Cases
Input
Run your code
Expected
[3, -1, 0, 1] [2, 2, 1, -1] [1, -1, 2, -1] [0, -1, 3, 4]
Expected program output
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.