日期:2026年10月25日
LeetCode 題目連結:1254. Number of Closed Islands
解題想法
中等難度題。題目給一個二維陣列 $grid$,其中 0 代表陸地,1 代表海洋。陸地可以與右、下、左、上相鄰的陸地相連,如果周圍被海洋環繞一圈,這片相連的陸地是一座島嶼。計算 $grid$ 之中有幾座島嶼。
這題是標準的 BFS。用雙層 for 迴圈掃過 $grid$ 每一格,如果遇到 0,可能是島嶼,用 is_island 標記是否為島嶼,預設為 True。接下來從這格開始 BFS,將走過的陸地都標示為 2,直接修改 $grid$ 的內容即可,節省記憶體。如果走的過程中出界,不是島嶼,is_land 改成 False。BFS 結束之後,如果 is_land 為 True,答案 $cnt + 1$。
Python 程式碼
Runtime: 12 ms, beats 87.91%. Memory: 19.76 MB, beats 75.00%.
from collections import deque
class Solution:
def closedIsland(self, grid: list[list[int]]) -> int:
m, n = len(grid), len(grid[0]) # 地圖尺寸 m*n
cnt = 0 # 島嶼數量
# 掃過 grid 每一格,遇到 0 用 BFS 走完相連的 0,走過的格子標記成 2
# 如果過程中會出界,不是島嶼
for i in range(m):
for j in range(n):
if grid[i][j] == 0:
is_island = True
que = deque([(i, j)])
grid[i][j] = 2
while que:
r, c = que.popleft()
for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
nr, nc = r + dr, c + dc
if nr < 0 or nr >= m or nc < 0 or nc >= n:
is_island = False
elif grid[nr][nc] == 0:
que.append((nr, nc))
grid[nr][nc] = 2
if is_island: cnt += 1
return cnt
C++ 程式碼
Runtime: 1 ms, beats 55.01%. Memory: 17.26 MB, beats 20.53%.
class Solution {
public:
int closedIsland(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size(); // 地圖尺寸 m*n
int cnt = 0; // 島嶼數量
int dr[4] = {0, 1, 0, -1}, dc[4] = {1, 0, -1, 0}; // 四方位檢查用的位移量
// 掃過 grid 每一格,遇到 0 用 BFS 走完相連的 0,走過的格子標記成 2
// 如果過程中會出界,不是島嶼
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if (grid[i][j] == 0) {
bool is_island = true;
queue<pair<int, int>> que;
que.push({i, j});
grid[i][j] = 2;
while(!que.empty()) {
int r = que.front().first, c = que.front().second;
que.pop();
for(int k = 0; k < 4; k++) {
int nr = r + dr[k], nc = c + dc[k];
if (nr < 0 || nr >= m || nc < 0 || nc >= n) {
is_island = false;
} else if (grid[nr][nc] == 0) {
que.push({nr, nc});
grid[nr][nc] = 2;
}
}
}
if (is_island) cnt++;
}
}
}
return cnt;
}
};
C 語言程式碼
Runtime: 1 ms, beats 37.50%. Memory: 9.86 MB, beats 91.67%.
typedef struct {
int r, c;
} Pos;
int closedIsland(int** grid, int gridSize, int* gridColSize) {
int m = gridSize, n = *gridColSize; // 地圖尺寸 m*n
int cnt = 0; // 島嶼數量
int dr[4] = {0, 1, 0, -1}, dc[4] = {1, 0, -1, 0}; // 四方位檢查用的位移量
// 掃過 grid 每一格,遇到 0 用 BFS 走完相連的 0,走過的格子標記成 2
// 如果過程中會出界,不是島嶼
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if (grid[i][j] == 0) {
int is_island = 1, head = 0, total = 1;
Pos que[10000]; // 最多走 100*100 格
que[0].r = i;
que[0].c = j;
grid[i][j] = 2;
while(head < total) {
int r = que[head].r, c = que[head].c;
head++;
for(int k = 0; k < 4; k++) {
int nr = r + dr[k], nc = c + dc[k];
if (nr < 0 || nr >= m || nc < 0 || nc >= n) {
is_island = 0;
} else if (grid[nr][nc] == 0) {
que[total].r = nr;
que[total].c = nc;
total++;
grid[nr][nc] = 2;
}
}
}
if (is_island) cnt++;
}
}
}
return cnt;
}
沒有留言:
張貼留言