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()
    

广搜理论基础

相关推荐
闻缺陷则喜何志丹19 小时前
【图论 组合数学】P10912 [蓝桥杯 2024 国 B] 数星星|普及+
c++·数学·蓝桥杯·图论
2301_764441331 天前
使用python构建的决策逻辑的图论
开发语言·python·图论
leoufung4 天前
组合问题:为什么用start避免重复
算法·深度优先·图论
mmz12075 天前
前缀和问题(c++)
c++·算法·图论
剪一朵云爱着6 天前
PAT 1131 Subway Map
算法·pat考试·图论
hakertop6 天前
如何基于C#读取.dot图论文件并和QuickGraph联动
数据库·c#·图论
烛衔溟6 天前
C语言图论:无向图基础
c语言·数据结构·图论·无向图
小李小李快乐不已6 天前
图论理论基础(5)
数据结构·c++·算法·机器学习·动态规划·图论
烛衔溟6 天前
C语言图论:有向图基础
c语言·数据结构·图论·有向图
zheyutao6 天前
割点和桥
算法·图论