图论 | 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()  
相关推荐
平乐君12 小时前
Leetcode刷题笔记1 图论part07
笔记·leetcode·图论
一只码代码的章鱼12 小时前
数据结构与算法-图论-强连通分量(tarjan算法)
数据结构·算法·图论
君义_noip13 小时前
信息学奥赛一本通 1514:【例 2】最大半连通子图 | 洛谷 P2272 [ZJOI2007] 最大半连通子图
c++·图论·信息学奥赛
平乐君1 天前
Leetcode 刷题笔记 图论part05
笔记·leetcode·图论
微臣愚钝1 天前
图论--最短路问题总结
算法·图论
哆啦A梦阳2 天前
14-图论-多源最短路径Floyd算法
算法·图论
平乐君3 天前
Leetcode刷题笔记1 图论part03
笔记·leetcode·图论
居然有人6543 天前
46.图论4
c++·算法·图论
寂空_3 天前
【算法笔记】图论基础(一):建图、存图、树和图的遍历、拓扑排序、最小生成树
笔记·算法·图论