图论 | 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()  
相关推荐
wuyk55512 小时前
18.Kruskal 算法:用最短的边连成一张网
开发语言·算法·图论
-dzk-14 小时前
【图论】LC 994.腐烂的橘子
图论
-dzk-1 天前
【图论】LC 200.岛屿数量
深度优先·图论
Lyyaoo.3 天前
【图论】岛屿数量/腐烂的橘子/课程表/实现前缀树
图论
lvwangshu4 天前
图论:LCA、树的直径、树的重心、二分图与 Tarjan 缩点
算法·图论
hansang_IR6 天前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
aqiu1111117 天前
【并查集 / 图论】蓝桥云课 - 魔法大陆的城市群(求无向图连通块数量)题解
蓝桥杯·图论
lvwangshu11 天前
P6534 [COCI 2015/2016 #1] UZASTOPNI 等差树列 题解
动态规划·图论·题解·性质题
positive_zpc15 天前
进阶数据结构图——关键路径(四)
数据结构·图论·关键路径
云淡风轻~窗明几净15 天前
宇宙管理学猜想
算法·图论