26 · Graphs: BFS & DFS

#286 Walls and Gates

frequently reported atMetaGoogleAmazonMicrosoft

the problem

In plain words

A floor plan is an m × n grid of ints: -1 is a wall, 0 is a gate, and 2147483647 (Integer.MAX_VALUE, call it INF) is an empty room. Fill every empty room, in place, with the number of steps (up, down, left, right) to its nearest gate. Walls can't be crossed. A room that can't reach any gate keeps INF.

in rooms = [[INF,-1,0,INF],[INF,INF,INF,-1],[INF,-1,INF,-1],[0,-1,INF,INF]]

out [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]

INF = 2147483647. The top-left room is 3 steps from the gate in the bottom-left corner.

in rooms = [[-1]]

out [[-1]]

Just a wall — nothing to fill.

  • 1 ≤ m, n ≤ 250
  • rooms[i][j] is -1, 0 or 2147483647

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code right here. Stuck for 20 minutes? Open one hint at a time.

This one is LeetCode Premium. You don't need a subscription: solve it right here. The free alternative linked above is the closest free practice; its label says how close it is.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #542
      01 Matrix
      Mediumin Graphs
    2. #994
      Rotting Oranges
      Mediumin Graphs
    3. #1730
      Shortest Path to Get Food
      Mediumin GraphsLeetCode Premium