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

广搜理论基础

相关推荐
闻缺陷则喜何志丹12 天前
【并集查找】P10729 [NOISG 2023 Qualification] Dolls|普及+
c++·算法·图论·洛谷·并集查找
CodeWithMe12 天前
【Algorithm】图论入门
c++·图论
东方芷兰14 天前
Leetcode 刷题记录 13 —— 图论
算法·leetcode·图论
蒙奇D索大15 天前
【数据结构】图论实战:DAG空间压缩术——42%存储优化实战解析
数据结构·笔记·学习·考研·图论·改行学it
蒙奇D索大19 天前
【数据结构】图论最短路圣器:Floyd算法如何用双矩阵征服负权图?
数据结构·算法·矩阵·图论·图搜索算法
芜湖xin20 天前
【题解-洛谷】B4292 [蓝桥杯青少年组省赛 2022] 路线
算法·图论·bfs·图的遍历
LunaGeeking21 天前
重要的城市(图论 最短路)
c++·算法·编程·图论·最短路·floyd
闻缺陷则喜何志丹21 天前
【强连通分量 拓扑序】P9431 [NAPC-#1] Stage3 - Jump Refreshers|普及+
c++·算法·图论·拓扑序·洛谷·强连通分量
蒙奇D索大24 天前
【数据结构】图论最短路径算法深度解析:从BFS基础到全算法综述
数据结构·算法·图论·广度优先·图搜索算法
计信金边罗1 个月前
是否存在路径(FIFOBB算法)
算法·蓝桥杯·图论