代码随想录图论

1. 所有可能的路径

python 复制代码
class Solution:
    def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
        
        def dfs(graph, result, path, root):     #result 返回结果, path记录路径, root记录遍历到了第几个节点
            if root == len(graph) - 1:          #如果遍历到最后一个节点,记录结果并返回
                result.append(path.copy())      
                return
            for i in graph[root]:               #遍历每个节点下一个能到的下一个节点
                path.append(i)                  #path直接添加
                dfs(graph, result, path, i)     #dfs递归, 输入的root直接变成i,也就是当前遍历的下一个
                path.pop()                      #回溯
        result = []
        path = [0]                              #初始化的时候path里已经有最初始的节点位置
        root = 0                                #起始节点为0
        dfs(graph, result, path, root)
        return result

实际上就是回溯算法,区别在于:之前做的回溯的题目一般是列表里面一个一个元素遍历,所以在递归的时候有一个start_index变量,控制选与不选当前元素。

而dfs搜索找下一个节点的时候,不用一个个遍历graph中的节点,而是只需要遍历当前节点能到达的节点,因为如果当前节点都到不了的节点,就没有必要往后遍历了。

因此递归的dfs的输入就变成了当前遍历的节点i

2. 岛屿数量

广搜 bfs版本

python 复制代码
class Solution:
    def __init__(self):
        self.dir = [(0, 1), (1, 0), (0, -1), (-1, 0)]
        self.count = 0

    def bfs(self, grid, visited, x, y):                                                     #广搜函数定义
        from collections import deque   
        queue = deque()                                                                     #初始化队列
        queue.append((x, y))                                                                #加入起始节点
        visited[x][y] = True                                                                #标记起始节点为已访问
        while queue:                                                                        #队列不为空进入循环
            curx, cury = queue.popleft()                                                    #取头节点
            for dx, dy in self.dir:                                                         #遍历四个方向
                nextx ,nexty = curx + dx, cury + dy                                     
                
                if nextx < 0 or nextx >= len(grid) or nexty < 0 or nexty >= len(grid[0]):   #越界就跳过
                    continue
                if grid[nextx][nexty] == "0":                                               #如果本题中是海水也跳过
                    continue
                if not visited[nextx][nexty]:                                               #把所有陆地标记为已访问
                    queue.append((nextx, nexty))
                    visited[nextx][nexty] = True
    
    def numIslands(self, grid: List[List[str]]) -> int:
        visited = [[False] * len(grid[0]) for _ in range(len(grid))]                        #初始化访问数组
        for i in range(len(grid)):
            for j in range(len(grid[0])):                                                   #遍历grid
                if visited[i][j] == False and grid[i][j] == "1":                            #如果节点没被访问过以及是陆地
                    self.count += 1                                                         #计数+1
                    self.bfs(grid, visited, i, j)                                           #深搜一下把当前节点连通的所有陆地都标记为已访问
        return self.count
        
相关推荐
Bruce_kaizy12 小时前
c++图论————最短路之Floyd&Dijkstra算法
c++·算法·图论
xu_yule14 小时前
算法基础(图论)—拓扑排序
c++·算法·动态规划·图论·拓扑排序·aov网
Andyshengwx1 天前
图论 最小生成树 MST问题
c++·算法·图论
賬號封禁中miu1 天前
图论之最小生成树
java·数据结构·算法·图论
脑海科技实验室1 天前
Ageing Res Rev:绘制阿尔茨海默病分期进展图:一项利用静息态fMRI和图论的综合性横断面及纵向研究
图论·fmri·阿尔茨海默病
闻缺陷则喜何志丹1 天前
【图论 拓扑排序 贪心 临项交换】P5603 小 C 与桌游 题解|普及+
c++·算法·图论·贪心·拓扑排序·洛谷·临项交换
闻缺陷则喜何志丹1 天前
【图论 BFS染色 并集查找 】P3663 [USACO17FEB] Why Did the Cow Cross the Road III S|普及+
c++·算法·图论·染色法·宽度优先·并集查找
青山如墨雨如画1 天前
【北邮-研-图论】网络最大流的标号算法V1.0
网络·算法·图论·北邮
xu_yule1 天前
算法基础-图论基础
数据结构·c++·算法·图论·dfs·bfs·最小生成树
_OP_CHEN1 天前
【算法基础篇】(三十七)图论基础之单源最短路:从原理到实战,4 大算法彻底吃透!
算法·图论