Walls And Gates

MediumGraphs
Asked byFacebookDoorDashGoogletiktokAmazonMicrosoft

Problem

Given a grid of rooms where -1 represents a wall, 0 represents a gate, and a large sentinel value represents an empty room, fill each empty room with the distance to its nearest gate. Leave rooms that can't reach a gate unchanged.

Examples

Example 1
Input:grid with a couple of gates and several empty rooms
Output:each empty room filled with its distance to the nearest gate

Constraints

  • 1 <= m, n <= 250

Solve it in the editor. Sign in free to run your Python or JavaScript against test cases, get a verdict, and track your attempts.

Solve on FeatCode →

How to approach it: the Graphs pattern

A graph models relationships as nodes and edges, which can be directed or undirected, weighted or not. Most graph problems come down to choosing the right traversal — DFS, BFS, or union-find — for what you're trying to find.

Look for this pattern when

  • The problem involves connections between items (islands, courses with prerequisites, friend networks, grids).
  • You need the shortest path in an unweighted graph (BFS) or need to explore every reachable node (DFS).
  • You're asking "are these two things connected?" repeatedly (union-find).

Read the full Graphs guide →

Video walkthroughs

Original problem on LeetCode ↗

More Graphs problems