day50 第十一章:图论part01

ACM模式,自己控制输入输出

图论理论基础

连通性:

连通图(无向),强连通图(有向)----- 任意两个节点之间都可相互到达

连通分量(极大连通子图),强连通分量

图的构造:

邻接矩阵

优点:

表达简单

易于查找任意2个顶点之间的连接

适合稠密图

缺点:

n*n,不适合稀疏图

邻接表

优点:

空间利用率高

缺点:

不好搜索任意2点之间是否存在

回溯就是深度优先搜索

邻接表和邻接矩阵dfs写法上没有太大差异

深搜理论基础

98. 所有可达路径

邻接矩阵:n*n的矩阵

python 复制代码
def main():
    n, m = map(int, input().split())
    graph = [[0]*(n+1) for _ in range(n+1)]
     
    for i in range(m):
        s, t = map(int, input().split())
        graph[s][t] = 1
     
    result = []
    path = [1]
    dfs(graph, 1, n, path, result)
     
    if not result:
        print(-1)
    else:
        for path in result:
            print(' '.join(map(str, path)))
     
     
def dfs(graph, x, n, path, result):
    if x==n:
        result.append(path.copy())
        return
    for i in range(1, n+1):
        if graph[x][i] == 1:
            path.append(i)
            dfs(graph, i, n, path, result)
            path.pop()
     
if __name__ == "__main__":
    main()

邻接表:defaultdict

python 复制代码
from collections import defaultdict

def main():
    n, m = map(int, input().split())
    graph = defaultdict(list)
    
    for i in range(m):
        s, t = map(int, input().split())
        graph[s].append(t)
    
    result = []
    path = [1]
    dfs(graph, 1, n, path, result)
    
    if not result:
        print(-1)
    else:
        for path in result:
            print(' '.join(map(str, path)))
    
def dfs(graph, x, n, path, result):
    if x == n:
        result.append(path.copy())
        return
    for i in graph[x]:
        # if graph[x][i] == 1:
        path.append(i)
        dfs(graph, i, n, path, result)
        path.pop()
    
if __name__ == "__main__":
    main()
    

广搜理论基础

相关推荐
天选之女wow4 小时前
【代码随想录算法训练营——Day61】图论——97.小明逛公园、127.骑士的攻击
算法·图论
天选之女wow1 天前
【代码随想录算法训练营——Day60】图论——94.城市间货物运输I、95.城市间货物运输II、96.城市间货物运输III
android·算法·图论
foundbug9991 天前
基于超像素和基于图论的图像分割方法
图论
CodeWizard~3 天前
AtCoder Beginner Contest 430赛后补题
c++·算法·图论
天选之女wow3 天前
【代码随想录算法训练营——Day58】图论——117.软件构建、47. 参加科学大会
算法·图论
earthzhang20214 天前
【2051】【例3.1】偶数
开发语言·数据结构·算法·青少年编程·图论
apcipot_rain4 天前
CSP集训错题集 第八周 主题:基础图论
算法·图论
天选之女wow4 天前
【代码随想录算法训练营——Day57(Day56周日休息)】图论——53.寻宝
算法·图论
极客数模5 天前
2025年(第六届)“大湾区杯”粤港澳金融数学建模竞赛准备!严格遵循要求,拿下大奖!
大数据·python·数学建模·金融·分类·图论·boosting
岑梓铭5 天前
《考研408数据结构》第七章(6.1~6.3图的概念、存储方式、深/广度遍历)复习笔记
数据结构·笔记·考研·算法·图论·408·ds