python学习笔记7-图的建立常用技巧

题目链接

  • 题目中给了邻接链表,转为邻接矩阵
  • 初始化邻接矩阵 graph = \[ for _ in range(n)]
  • dfs() 的写法, 用visi避免重复访问,得到每个点所在的联通分量中点的个数
python 复制代码
class Solution:
    def countPairs(self, n: int, edges: List[List[int]]) -> int:
        graph = [[] for _ in range(n)]
        for x, y in edges:
            graph[x].append(y)
            graph[y].append(x)
        
        visi = [False] * n
        def dfs(x: int) -> int:
            visi[x] = True
            count = 1
            for y in graph[x]:
                if not visi[y]:
                    count += dfs(y)
            return count

        res = 0
        for i in range(n):
            if not visi[i]:
                count = dfs(i)
                res += count * (n - count)

        return res // 2
相关推荐
打工仔折腾 AI2 分钟前
Prometheus 告警推钉钉:从单群 Webhook 到跨网络 Alertmanager 实战
人工智能·后端·python·性能优化
Ivanqhz7 分钟前
Ping-Pong 双缓冲
开发语言·人工智能·python·深度学习·mlir
三十岁老牛再出发7 分钟前
9月18日总结
python·深度学习·机器学习
就叫你天选之人啦19 分钟前
安装torch+vllm+flash_attn的prompt
人工智能·pytorch·python
wuyk5551 小时前
21.计数排序:不用比较的“空间换时间”排序算法
python·算法·排序算法
智码看视界1 小时前
第4篇:循环神经网络及其变体 LSTM/GRU 实战
python·自然语言处理·gru·lstm·循环神经网络·情感分析·梯度消失
Web3&Basketball1 小时前
Agent外传审计实战:3类失准事故拦截脚本
python·大模型·agent·性能调优·推理优化
何以解忧,唯有..1 小时前
Milvus 向量数据库的 DDL、DML、DQL 操作详解
python
罗狮粉 991 小时前
AI-Gateway — 面向 AI Agent 的本地 Runtime Gateway
人工智能·python·inscode·ai编程
蓝胖的四次元口袋1 小时前
Python数据结构知识梳理
python