【代码随想录训练营】【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)
        
    
相关推荐
wwer1425263636 小时前
数学建模_图论
数学建模·图论
ysa05103013 小时前
Dijkstra 算法#图论
数据结构·算法·图论
一只鱼^_18 小时前
基础算法合集-图论
数据结构·算法·深度优先·图论·广度优先·宽度优先·图搜索算法
闻缺陷则喜何志丹13 天前
【并集查找】P10729 [NOISG 2023 Qualification] Dolls|普及+
c++·算法·图论·洛谷·并集查找
CodeWithMe13 天前
【Algorithm】图论入门
c++·图论
东方芷兰15 天前
Leetcode 刷题记录 13 —— 图论
算法·leetcode·图论
蒙奇D索大17 天前
【数据结构】图论实战:DAG空间压缩术——42%存储优化实战解析
数据结构·笔记·学习·考研·图论·改行学it
蒙奇D索大20 天前
【数据结构】图论最短路圣器:Floyd算法如何用双矩阵征服负权图?
数据结构·算法·矩阵·图论·图搜索算法
芜湖xin21 天前
【题解-洛谷】B4292 [蓝桥杯青少年组省赛 2022] 路线
算法·图论·bfs·图的遍历
LunaGeeking22 天前
重要的城市(图论 最短路)
c++·算法·编程·图论·最短路·floyd