PIXELBANKv9.1.0
Menu

Given an m x n grid where:

  • -1 = wall
  • 0 = gate
  • 2147483647 = empty room

Fill each empty room with the distance to its nearest gate. If impossible, leave it as 2147483647.

Output the grid, each row on a new line, values space-separated.

Example:

Input:
2147483647,-1,0,2147483647
2147483647,2147483647,2147483647,-1
2147483647,-1,2147483647,-1
0,-1,2147483647,2147483647
Output:
3 -1 0 1
2 2 1 -1
1 -1 2 -1
0 -1 3 4
Reasoning:
  • The algorithm starts by identifying the gates in the grid, which are the cells with a value of 00.
  • It then performs a breadth-first search (BFS) from each gate, incrementing the distance by 11 as it moves to adjacent empty rooms.
  • During the BFS, the algorithm updates the distance of each empty room to be the minimum distance from any gate, effectively filling in the grid with the distance to the nearest gate.
  • The final output is the resulting grid, where each empty room contains its distance to the nearest gate, and walls remain as −1-1.

Constraints:

  • 1 <= rows, cols <= 250
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Walls and Gates - Medium | PixelBank