150強訪談簡單

島嶼最大面積

「島嶼最大面積」問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個 m x n 二進位矩陣網格。島嶼是一組 4 個方向(水平或垂直)相連的 1(代表陸地)。您可以假設網格的所有四個邊緣都被水包圍。

島嶼的面積是島上值為 1 的單元格的數量。

返回網格中島嶼的最大面積。如果沒有島嶼,則回傳0。

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

約束條件
  • m == len(grid)
  • n == len(grid[i])
  • 1 <= m, n <= 50
  • grid[i][j] is 0 or 1

範例

Example 1
Input
grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Output
6
Explanation

The maximum area of an island is 6, located in the lower-right part of the grid.

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

There are no islands in the grid, so the max area is 0.

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

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