150強訪談簡單

在上升的水中游泳

「在上升的水中游泳」問題的詳細指南和 Python 實現。

問題陳述

簡單

給定一個 n x n 整數矩陣網格,其中每個值 grid[i][j] 表示該點 (i, j) 的海拔。雨開始下。在t時刻,各處水深為t。當且僅當方格中的兩個高程都至多為 t 時,你才能從一個方格游到另一個 4 方向相鄰的方格。

從左上角的方塊 (0, 0) 開始。到達右下方格 (n-1, n-1) 所需的最短時間是多少?

寫一個函數 swimInWater(grid: List[List[int]]) -> int

約束條件
  • n == len(grid) == len(grid[i])
  • 1 <= n <= 50
  • 0 <= grid[i][j] < n^2
  • Each value grid[i][j] is unique

範例

Example 1
Input
grid = [[0,2],[1,3]]
Output
3
Explanation

At time 3, you are permitted to swim all the way from (0,0) to (1,1). The path is 0 -> 1 -> 3.

Example 2
Input
grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]
Output
16
Explanation

The final path is 0-1-2-3-4-5-16-15-14-13-12-11-10-9-8-7-6. The maximum height along this path is 16.

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

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