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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。