【代码随想录算法训练营——Day50(Day49周日休息)】图论——98.所有可达路径

卡码网题目链接

https://kamacoder.com/problempage.php?pid=1170

题解
98.所有可达路径

想套用深搜或广搜的代码模板。看了一下题解的开头给了一点提示,要用深搜的模板。写了一个充满不确定性的dfs代码,让deepseek过目了一下,改了很多地方,因为是照着我的代码改的,所以改的也不对,原因如下。再看看题解。看了题解,感觉好简单,但自己写的时候就缺乏很多细节。





代码

python 复制代码
#98.所有可达路径
#邻接矩阵法
result = []
path = []
def dfs(graph, cur, n):
    if cur == n:
        result.append(path.copy())
        return
    for i in range(1, n + 1):
        if graph[cur][i] == 1:
            path.append(i)
            dfs(graph, i, n)
            path.pop()

if __name__ == "__main__":
    n, m = map(int, input().split())
    graph = [[0] * (n + 1) for _ in range(n + 1)]
    for i in range(m):
        start, end = map(int, input().split())
        graph[start][end] = 1
    path.append(1)
    dfs(graph, 1, n)
    if len(result) == 0:
        print("-1")
    for i in range(len(result)):
        for j in range(len(result[i]) - 1):
            print(f"{result[i][j]} ", end = '')
        print(result[i][len(result[i]) - 1])

#邻接表法
from collections import defaultdict

result = []
path = []
def dfs(graph, cur, n):
    if cur == n:
        result.append(path.copy())
        return
    for i in range(1, n + 1):
        if i in graph[cur]:
            path.append(i)
            dfs(graph, i, n)
            path.pop()

if __name__ == "__main__":
    n, m = map(int, input().split())
    graph = defaultdict(list)
    for i in range(m):
        start, end = map(int, input().split())
        graph[start].append(end)
    path.append(1)
    dfs(graph, 1, n)
    if len(result) == 0:
        print("-1")
    for i in range(len(result)):
        for j in range(len(result[i]) - 1):
            print(f"{result[i][j]} ", end = '')
        print(result[i][len(result[i]) - 1])
相关推荐
!停14 分钟前
C语言单链表
c语言·数据结构·算法
闻缺陷则喜何志丹24 分钟前
【回文 字符串】3677 统计二进制回文数字的数目|2223
c++·算法·字符串·力扣·回文
Tisfy31 分钟前
LeetCode 0085.最大矩形:单调栈
算法·leetcode·题解·单调栈
mit6.82432 分钟前
出入度|bfs|状压dp
算法
hweiyu0033 分钟前
强连通分量算法:Kosaraju算法
算法·深度优先
源代码•宸34 分钟前
Golang语法进阶(定时器)
开发语言·经验分享·后端·算法·golang·timer·ticker
mit6.82440 分钟前
逆向思维|memo
算法
机器学习之心42 分钟前
MATLAB灰狼优化算法(GWO)改进物理信息神经网络(PINN)光伏功率预测
神经网络·算法·matlab·物理信息神经网络
代码游侠1 小时前
学习笔记——ESP8266 WiFi模块
服务器·c语言·开发语言·数据结构·算法
倦王1 小时前
力扣日刷26110
算法·leetcode·职场和发展