图论入门编程

卡码网刷题链接:98. 所有可达路径

一、题目简述

二、编程demo

方法①邻接矩阵

python 复制代码
from collections import defaultdict
#简历邻接矩阵
def build_graph(): 
    n, m = map(int,input().split()) 
    graph = [[0 for _ in range(n+1)] for _ in range(n+1)]
    for _ in range(m): 
        i,j = map(int,input().split()) 
        graph[i][j] = 1
    return graph,n
#深度优先搜索
def dfs(g,r,i,end,path):
    if i == end:
        r.append(path.copy())
        return 
    for k in range(1,end+1):
        if g[i][k]:
            path.append(k)
            dfs(g,r,k,end,path)
            path.pop()
    return 
#主函数
def main():
    graph,n = build_graph()
    result = []
    path = [1]
    dfs(graph,result,1,n,path)
    #按格式打印输出
    if not result:
        print(-1)
    for p in result:
        print(" ".join(map(str,p)))
    return 
if __name__ == "__main__":
    main()

方法②邻接表

python 复制代码
from collections import defaultdict
def build_graph(): 
    n, m = map(int,input().split()) 
    graph = defaultdict(list) 
    for _ in range(m): 
        i,j = map(int,input().split()) 
        graph[i].append(j)
    return graph,n

def dfs(g,r,i,end,path):
    if i == end:
        r.append(path.copy())
        return 
    for k in g[i]:
        path.append(k)
        dfs(g,r,k,end,path)
        path.pop()
    return 

def main():
    graph,n = build_graph()
    result = []
    path = [1]
    dfs(graph,result,1,n,path)
    if not result:
        print(-1)
    for p in result:
        print(" ".join(map(str,p)))
    return 
if __name__ == "__main__":
    main()
相关推荐
程序员东岸4 小时前
《数据结构——排序(中)》选择与交换的艺术:从直接选择到堆排序的性能跃迁
数据结构·笔记·算法·leetcode·排序算法
程序员-King.4 小时前
day104—对向双指针—接雨水(LeetCode-42)
算法·贪心算法
神仙别闹4 小时前
基于C++实现(控制台)应用递推法完成经典型算法的应用
开发语言·c++·算法
Ayanami_Reii4 小时前
进阶数据结构应用-一个简单的整数问题2(线段树解法)
数据结构·算法·线段树·延迟标记
listhi5205 小时前
基于改进SET的时频分析MATLAB实现
开发语言·算法·matlab
Keep_Trying_Go6 小时前
基于Zero-Shot的目标计数算法详解(Open-world Text-specified Object Counting)
人工智能·pytorch·python·算法·多模态·目标统计
xl.liu6 小时前
零售行业仓库商品数据标记
算法·零售
confiself6 小时前
通义灵码分析ms-swift框架中CHORD算法实现
开发语言·算法·swift
做怪小疯子6 小时前
LeetCode 热题 100——二叉树——二叉树的层序遍历&将有序数组转换为二叉搜索树
算法·leetcode·职场和发展
CoderYanger6 小时前
递归、搜索与回溯-记忆化搜索:38.最长递增子序列
java·算法·leetcode·1024程序员节