150強訪談中等

矩陣中最長的遞增路徑

“矩陣中最長遞增路徑”問題的詳細指南和 Python 實作。

問題陳述

中等

給定一個 m x n 整數矩陣,傳回矩陣中最長遞增路徑的長度。

在每個單元格中,您可以向四個方向移動:左、右、上或下。您不得沿對角線移動或移出邊界(即不允許環繞)。

寫一個函數 longestIncreasingPath(matrix: List[List[int]]) -> int

約束條件
  • m == len(matrix)
  • n == len(matrix[0])
  • 1 <= m, n <= 200
  • 0 <= matrix[i][j] <= 2^31 - 1

範例

Example 1
Input
matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output
4
Explanation

The longest increasing path is [1, 2, 6, 9].

Example 2
Input
matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output
4
Explanation

The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

Need a Hint?
考慮使用 2D DP 特定的資料結構,例如集合或堆疊。
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 資源

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