图论 | 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()  
相关推荐
handler011 天前
【算法】并查集(普通/扩展/带权)模板与例题
数据结构·c++·笔记·算法·c·图论·查并集
Lsk_Smion1 天前
力扣实训 _ [994].腐烂的橘子/图论
算法·leetcode·图论
Lucis__1 天前
图的高阶算法:从构造最小生成树到求解最短路径问题
数据结构·c++·算法·图论
随意起个昵称2 天前
线性dp-LIS题目2(导弹拦截III)
算法·动态规划·图论
05候补工程师2 天前
【408 数据结构】图论核心算法(拓扑/关键路径)与二叉搜索树精髓夺分笔记
数据结构·经验分享·笔记·考研·算法·图论
江屿风4 天前
C++图的两种构建算法流食般投喂-竞赛编
开发语言·c++·笔记·算法·图论
代码中介商4 天前
图论入门:从基础到遍历算法
数据结构·算法·图论
一个爱编程的人5 天前
图的相关概念
c++·算法·图论
05候补工程师5 天前
【408数据结构】核心考点:图(Graph)精炼笔记与算法直觉
数据结构·经验分享·笔记·考研·算法·图论
嘿黑嘿呦6 天前
数据结构-图论-最小生成树
数据结构·算法·图论