程式碼隨想錄演算法訓練營day51| 卡碼網99.島嶼數量 卡碼網100.島嶼的最大面積

Tristan241001發表於2024-11-19

學習資料:https://www.programmercarl.com/kamacoder/0099.島嶼的數量深搜.html#思路

深度優先搜尋和廣度優先搜尋
今天用的鄰接矩陣

學習記錄:
卡碼網99.島嶼數量 (深搜or廣搜;用一個自己設計的二維矩陣來控制節點的移動方向:上下左右)

點選檢視程式碼
from collections import deque
direction = [[1,0], [0,1], [-1,0], [0, -1]]  # 上,右,下,左

def bfs(visited, grid, x, y):
    """廣搜"""
    que = deque([])
    que.append([x, y])
    while que:
        cur_x, cur_y = que.popleft()
        for i, j in direction:
            next_x = cur_x + i
            next_y = cur_y + j
            if next_x<0 or next_x>=len(grid) or next_y<0 or next_y>=len(grid[0]):
                continue
            if not visited[next_x][next_y] and grid[next_x][next_y] == 1:
                visited[next_x][next_y] = True
                que.append([next_x, next_y])
    


def dfs(visited, grid, x, y):
    """深搜"""
    for i, j in direction:
        next_x = x+i
        next_y = y + j
        # 下標越界,跳過 (這一小片區域的邊界)
        if next_x<0 or next_x>=len(grid) or next_y<0 or next_y>=len(grid[0]):
            continue
        # 遇到為訪問的陸地,標記並使用深搜
        if not visited[next_x][next_y] and grid[next_x][next_y]==1:
            visited[next_x][next_y] = True
            dfs(visited, grid, next_x, next_y)

if __name__ == "__main__":
    n, m = map(int, input().split())
    
    # 構造鄰接矩陣
    grid = []
    for i in range(n):
        grid.append(list(map(int, input().split())))
    
    # 構造訪問表,若以訪問則為True
    visited = [[False]*m for _ in range(n)]
    
    # 島嶼數量
    res = 0
    
    for i in range(n):
        for j in range(m):
            # 如果當前是陸地,且未被訪問過,說明找到了一片新的陸地,標記該訪問情況,深搜找這片的範圍
            if grid[i][j] == 1 and not visited[i][j]:
                res += 1
                visited[i][j] = True
                bfs(visited, grid, i, j)   # dfs(visited, grid, i, j) 也可以
    
    print(res)

卡碼網100.島嶼的最大面積(深搜法;給前面這道題的基礎上,遍歷每片島嶼時,要記錄每個陸地值得到島嶼面積)

點選檢視程式碼
directions = [[1,0],[0,1],[-1,0],[0,-1]]
count = 0

def dfs(visited, grid, x, y):
    global count   # 設定全域性變數
    for i,j in directions:
        cur_x = x + i
        cur_y = y + j
        if cur_x<0 or cur_x>=len(grid) or cur_y<0 or cur_y>=len(grid[0]):
            continue
        if not visited[cur_x][cur_y] and grid[cur_x][cur_y]==1:
            visited[cur_x][cur_y] = True
            count += 1
            dfs(visited, grid, cur_x, cur_y)



n, m = map(int, input().split())

grid = []
for i in range(n):
    grid.append(list(map(int, input().split())))
    
visited = [[False]*m for _ in range(n)]

result = 0     # 記錄count的最大值

for i in range(n):
    for j in range(m):
        if grid[i][j]==1 and not visited[i][j]:
            count = 1
            visited[i][j] = True
            dfs(visited, grid, i, j)
            result = max(result, count)

print(result)

PS:不想學習的一天,想念卡哥影片的一天,啥時候出圖論啊
學的比較潦草,多複習
好冷,今天吃了好多美食,豆花牛肉、大盤雞、涼皮、羊肉抓飯、冰淇淋,嗝~
讓我們一起倒數十個數!

相關文章