【代码随想录训练营】【Day 65】【图论-2】| 卡码 99

【代码随想录训练营】【Day 65】【图论-2】| 卡码 99

需强化知识点

  • 深度搜索和广度搜索

题目

99. 岛屿数量

思想:遍历到为1的节点,再搜索标记,每遇到新的陆地节点,增加计数

  • 深度搜索
  • 广度搜索:此处用 [] 作为待遍历队列也可,que(append,popleft)
python 复制代码
import collections

def dfs(grid, visited, x, y):
    dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
    for add_x, add_y in dirs:
        next_x = x + add_x
        next_y = y + add_y
        
        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]:
            visited[next_x][next_y] = True
            dfs(grid, visited, next_x, next_y)

def bfs(grid, visited, x, y):
    dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
    que = collections.deque()
    # que = []
    que.append([x, y])
    visited[x][y] = True
    while que:
        # cur = que.pop()
        cur = que.popleft()
        cur_x = cur[0]
        cur_y = cur[1]
        for add_x, add_y in dirs:
            next_x = cur_x + add_x
            next_y = cur_y + add_y
        
            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]:
                que.append([next_x, next_y])
                visited[next_x][next_y] = True
        
        

tmp = list(map(int, input().split()))
m, n = tmp[0], tmp[1]

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

result = 0
for i in range(m):
    for j in range(n):
        if not visited[i][j] and grid[i][j]:
            visited[i][j] = True
            result += 1
            bfs(grid, visited, i, j)

print(result)
        
    
相关推荐
散11216 小时前
01数据结构-Prim算法
数据结构·算法·图论
KyollBM20 小时前
【图论】分层图 / 拆点
图论
GawynKing1 天前
图论(5)最小生成树算法
算法·图论·最小生成树
KarrySmile1 天前
Day60--图论--94. 城市间货物运输 I(卡码网),95. 城市间货物运输 II(卡码网),96. 城市间货物运输 III(卡码网)
图论·spfa·bellman_ford·队列优化·最短路算法·负权回路·单源有限最短路
花开富贵ii1 天前
代码随想录算法训练营四十三天|图论part01
java·数据结构·算法·深度优先·图论
yi.Ist2 天前
图论——Djikstra最短路
数据结构·学习·算法·图论·好难
KarrySmile2 天前
Day55--图论--107. 寻找存在的路径(卡码网)
图论·并查集·寻找存在的路径
KarrySmile2 天前
Day62--图论--97. 小明逛公园(卡码网),127. 骑士的攻击(卡码网)
图论·floyd·floyd算法·弗洛伊德算法·astar算法·小明逛公园·骑士的攻击
Morriser莫3 天前
图论Day2学习心得
算法·图论
KarrySmile3 天前
Day53--图论--106. 岛屿的周长(卡码网),110. 字符串接龙(卡码网),105. 有向图的完全联通(卡码网)
深度优先·图论·广度优先·广搜·岛屿的周长·字符串接龙·有向图的完全联通