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
相关推荐
斯班奇的好朋友阿法法9 小时前
Django 3.2 项目:从 Hello World 开始(完整功能版)
python·django
架构师老Y9 小时前
010:API网关调试手记:路由、认证与限流的那些坑
开发语言·前端·python
老刘说AI9 小时前
Dify:从入门到精通
人工智能·python·神经网络·低代码·ai作画·开源软件
zhangzeyuaaa9 小时前
Python 闭包详解
开发语言·python
万粉变现经纪人9 小时前
如何解决 pip install tensorflow-gpu 报错 未检测到 CUDA 驱动 问题
人工智能·python·深度学习·aigc·tensorflow·bug·pip
架构师老Y9 小时前
009、容器编排实战:Kubernetes上的Python服务
python·容器·kubernetes
Freak嵌入式9 小时前
MicroPython LVGL基础知识和概念:底层渲染与性能优化
人工智能·python·单片机·性能优化·嵌入式·lvgl·micropython
ZhengEnCi15 小时前
M3-markconv库找不到wkhtmltopdf问题
python
2301_7644413318 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
chushiyunen19 小时前
python rest请求、requests
开发语言·python