Leetcode 200. 島嶼數量
難度:中等
給定一個由
'1'
(陸地)和'0'
(水)組成的的二維網格,計算島嶼的數量。一個島被水包圍,並且它是通過水平方向或垂直方向上相鄰的陸地連接而成的。你可以假設網格的四個邊均被水包圍。示例 1:
輸入: 11110 11010 11000 00000 輸出: 1
示例 2:
輸入: 11000 11000 00100 00011 輸出: 3
題解:
- 設定上、下、左、右方向。
- 從開始遍歷,遍歷過的位置做標記,即重寫爲“Y”。
- 廣度優先,維護一隊列,遍歷的元素進隊列,先進先出。
- 出列的比較上、下、左、右是否含“1”(連通),將含有的進隊列。
- 隊列空一次,表示本次連通的統計已經完畢,島嶼數要+1。
- 只需比較當前位置上、下、左、右各一步就可以。
BFS:
from typing import List
from collections import deque
class Solution:
# 當前位置的四個方向偏移量
directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]
def numIslands(self, grid: List[List[str]]) -> int:
m = len(grid)
# 特判
if m == 0:
return 0
n = len(grid[0])
count = 0
# 從第一行第一列開始使用BFS搜索
for i in range(m):
for j in range(n):
# 用BFS找連通的陸地,條件是沒有被訪問過的陸地,一旦訪問立即標記
if grid[i][j]!='Y' and grid[i][j] == '1':
# 連通的堆數計數
count += 1
queue = deque()
# 滿足條件進入隊列
queue.append((i, j))
# 同時標記已訪問
grid[i][j] = 'Y'
while queue:
cur_x, cur_y = queue.popleft()
# 當前位置上下左右方向上
for direction in self.directions:
new_i = cur_x + direction[0]
new_j = cur_y + direction[1]
# 判定越界情況
# 判斷是否被訪問
# 判斷陸地
if 0 <= new_i < m and 0 <= new_j < n and grid[new_i][new_j]!='Y' and grid[new_i][new_j] == '1':
# 滿足條件,進隊列
queue.append((new_i, new_j))
# 同時標記已訪問
grid[new_i][new_j] = 'Y'
return count