图论 | 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()  
相关推荐
浩瀚星辰202413 小时前
图论基础算法:DFS、BFS、并查集与拓扑排序的Java实现
java·算法·深度优先·图论
lcg_magic2 天前
图论系列(一):基础概念与术语解析
图论
127_127_1276 天前
2025 FJCPC 复建 VP
数据结构·图论·模拟·ad-hoc·分治·转化
wwer1425263636 天前
数学建模_图论
数学建模·图论
ysa0510306 天前
Dijkstra 算法#图论
数据结构·算法·图论
一只鱼^_7 天前
基础算法合集-图论
数据结构·算法·深度优先·图论·广度优先·宽度优先·图搜索算法
ysa0510307 天前
图论基础算法入门笔记
数据结构·c++·笔记·算法·图论
闻缺陷则喜何志丹19 天前
【并集查找】P10729 [NOISG 2023 Qualification] Dolls|普及+
c++·算法·图论·洛谷·并集查找
CodeWithMe19 天前
【Algorithm】图论入门
c++·图论
东方芷兰21 天前
Leetcode 刷题记录 13 —— 图论
算法·leetcode·图论