150強訪談簡單

島嶼數量

“島嶼數量”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個 m x n 二維二進位網格,它代表「1」(陸地)和「0」(水)的地圖,返回島嶼的數量。

島嶼四面環水,相鄰陸地水平或垂直連接而成。您可以假設網格的所有四個邊緣都被水包圍。

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

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

範例

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

There is a single island consisting of all connected '1's starting from top-left.

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

There are three distinct islands separated by '0's.

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

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