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
相关推荐
Eric.Lee2021几秒前
python opencv 将不同shape尺寸的图片制作video视频
python·opencv·音视频
Amo Xiang11 分钟前
Python 常用模块(八):logging模块
python·logging·日志
森哥的歌13 分钟前
Python多线程
python·编程·多线程·并发·threading
抽风的雨61036 分钟前
【python基础知识】Day26 函数
开发语言·python
编程有点难1 小时前
Python训练打卡Day22
开发语言·python·机器学习
天机️灵韵2 小时前
字节开源FlowGram与n8n 技术选型
人工智能·python·开源项目
兮兮能吃能睡2 小时前
Python之with语句
数据库·python
boooo_hhh2 小时前
第28周——InceptionV1实现猴痘识别
python·深度学习·机器学习
咕噜咕噜啦啦2 小时前
Python爬虫入门
开发语言·爬虫·python
dubochao_xinxi2 小时前
✅ TensorRT Python 安装精简流程(适用于 Ubuntu 20.04+)
开发语言·python·ubuntu