150强访谈简单

墙和门

“墙和门”问题的详细指南和 Python 实现。

问题陈述

简单

给你一个 m x n 网格房间,用这三个可能的值初始化:

- -1:墙壁或障碍物。

- 0:门。

- INF(由2147483647代表):一个空房间。

用到最近大门的距离填充每个空房间。如果无法到达某个门,则应填充 INF。

编写一个函数 wallsAndGates(rooms: List[List[int]]) -> List[List[int]] 返回修改后的房间网格。

约束条件
  • m == len(rooms)
  • n == len(rooms[i])
  • 1 <= m, n <= 250
  • rooms[i][j] is -1, 0, or 2147483647

示例

Example 1
Input
rooms = [[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]]
Explanation

The empty rooms are filled with the shortest distance to their nearest gate.

Need a Hint?
考虑使用特定于图的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。