【代码随想录训练营】【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)
        
    
相关推荐
JK0x071 天前
代码随想录算法训练营 Day61 图论ⅩⅠ Floyd A※ 最短路径算法
算法·图论
qq_447429411 天前
数据结构与算法:图论——拓扑排序
linux·c语言·学习·图论
zc.ovo2 天前
图论刷题1
算法·深度优先·图论
珂朵莉MM2 天前
2022 RoboCom 世界机器人开发者大赛-本科组(省赛)解题报告 | 珂学家
人工智能·算法·职场和发展·深度优先·图论
蒙奇D索大2 天前
【数据结构】图论核心算法解析:深度优先搜索(DFS)的纵深遍历与生成树实战指南
数据结构·算法·深度优先·图论·图搜索算法
ShiinaMashirol2 天前
代码随想录打卡|Day50 图论(拓扑排序精讲 、dijkstra(朴素版)精讲 )
java·图论
JK0x074 天前
代码随想录算法训练营 Day60 图论Ⅹ Bellmen_ford 系列算法
android·算法·图论
ShiinaMashirol4 天前
代码随想录打卡|Day53 图论(Floyd 算法精讲 、A * 算法精讲 (A star算法)、最短路算法总结篇、图论总结 )
算法·图论
KyollBM5 天前
【CF】Day69——⭐Codeforces Round 897 (Div. 2) D (图论 | 思维 | DFS | 环)
算法·深度优先·图论
橙留香mostarrain5 天前
从零开始的数据结构教程(四) 图论基础与算法实战
数据结构·算法·图论