DIY: Walls and Gates

Solve the interview question "Walls and Gates" in this lesson.

We'll cover the following


You are given a m×nm \times n grid represented by a 2D array named rooms. The grid represents rooms where a cell can either be a wall, a gate, or an empty space. The rooms are initialized with these three possible values.

Values Represents
1-1 A wall or an obstacle
00 A gate
2311=21474836472^{31} - 1 = 2147483647 An empty room

For an empty room, you should assume that the distance to a gate is less than 21474836472147483647. We will call this value INF as an infinity value, where infinity represents an empty room.

Fill each empty room with the distance to its nearest gate. If it is impossible to reach a particular gate, you will fill it with the value INF.


  • m == rooms.length
  • n == rooms[i].length
  • 1 <= m, n <= 250
  • rooms[i][j] is 1-1, 00, or 23112^{31} - 1.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.