图论 | 98. 所有可达路径

98. 所有可达路径

题目链接: 98. 所有可达路径

思路

  1. 先创建邻接矩阵,再深搜
  2. 写代码是需要注意的是acm格式,输入的格式要转化为int,输出要转化为str,用map()实现。

dfs

python 复制代码
def dfs(grid,node,n,path,res):
    if node == n:
        res.append(path[:])
        return
    for j in range(len(grid[0])):
        if grid[node-1][j] == 1:
            path.append(j+1)
            dfs(grid,j+1,n,path,res)
            path.pop()

def main():
    # 构造邻接矩阵
    n,m = map(int,input().split())
    grid = [[0]*n for _ in range(n)]
    for _ in range(m):
        node1,node2 = map(int,input().split())
        grid[node1-1][node2-1] = 1

    res = []
    dfs(grid,1,n,[1],res)
    if not res:
        print(-1)
    else:
        for path in res:
            print(' '.join(map(str,path)))
    

if __name__ == "__main__":
    main()  
相关推荐
希望20173 天前
图论基础知识
算法·图论
行走的bug...4 天前
用图论来解决问题
算法·图论
Athenaand4 天前
代码随想录算法训练营第50天 | 图论理论基础、深搜理论基础、98. 所有可达路径、广搜理论基础
算法·图论
_Coin_-5 天前
算法训练营DAY60 第十一章:图论part11
算法·图论
Athenaand5 天前
代码随想录算法训练营第62天 | Floyd 算法精讲、A * 算法精讲 (A star算法)、最短路算法总结篇、图论总结
算法·图论
ZLRRLZ6 天前
【数据结构】图
数据结构·算法·图论
一只鱼^_10 天前
牛客周赛 Round 108
数据结构·c++·算法·动态规划·图论·广度优先·推荐算法
_Coin_-10 天前
算法训练营DAY58 第十一章:图论part08
数据结构·算法·图论
闪电麦坤9513 天前
数据结构:图的表示 (Representation of Graphs)
数据结构·算法·图论
BlackPercy13 天前
【图论】Graphs.jl 最小生成树算法文档
算法·图论