图论 | 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()  
相关推荐
positive_zpc14 小时前
进阶数据结构图——关键路径(四)
数据结构·图论·关键路径
云淡风轻~窗明几净1 天前
宇宙管理学猜想
算法·图论
小星星闪亮登场2 天前
图论--最小生成树(内含二分图)
数据结构·算法·图论·迭代加深·图搜索算法
positive_zpc2 天前
进阶数据结构图——最短路径(二)
数据结构·算法·图论·最短路径
positive_zpc2 天前
进阶数据结构图——最小生成树(一)
数据结构·算法·图论
无定义_3 天前
Dijkstra——单源最短路径
算法·图论
zmzb01033 天前
C++课后习题训练记录Day201
c++·算法·图论
星星.7223 天前
【图论】最小生成树|Prim+Kruskal算法
数据结构·c++·算法·图论
微小冷5 天前
Python图论库NetworkX初步
开发语言·python·图论·graph·networkx·digraph
珂朵莉MM6 天前
2026国信杯具身智能创新大赛-编程技能赛--本科组国赛解题报告 | 珂学家
算法·深度优先·图论