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
相关推荐
Hachi被抢先注册了14 小时前
Skills总结
python
用户03321266636714 小时前
使用 Python 在 PowerPoint 中创建折线图和条形图
python
benchmark_cc14 小时前
如何用 Python 进行多周期 K 线合成与时区对齐?基于 QuantDash 与 Pandas 的量化数据清洗实战(附 GitHub 源码)
开发语言·python·github·盯盘·pandas·quantdash·量化数据
不如语冰14 小时前
AI大模型入门-参数的传递
数据结构·人工智能·pytorch·python
用户67608406561714 小时前
GraphBLAS_01_图的稀疏表示
python
小陈工14 小时前
第7篇:Django框架核心原理与实战深度解析(下)
后端·python·面试
用户2986985301415 小时前
Python 数据处理:XML 与 Excel 互转的实用指南
后端·python·excel
m0_6174939415 小时前
PyCharm 新手避坑指南:一文解决“项目列表消失”与“模块导入报错”两大玄学问题
ide·python·pycharm
中微极客15 小时前
从Prompt到RAG:LLM工程实战全链路解析
人工智能·python·prompt
就牙白15 小时前
中科方德服务器打包RPM
linux·python