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
相关推荐
RSABLOCKCHAIN6 小时前
AI Agents in LangGraph-2
人工智能·python
WA内核拾荒者7 小时前
WhatsApp 账号异常检测的自动化告警系统设计
数据库·python·自动化
码流怪侠8 小时前
【GitHub】Bend:让 GPU 并行编程像写 Python 一样简单
python·github
2401_894915539 小时前
GEO 搜索优化完整源码从零部署:环境配置、集群搭建全流程
开发语言·python·tcp/ip·算法·unity
zhiSiBuYu051710 小时前
Python3 模块开发与应用实战指南
python
databook11 小时前
用方差阈值过滤掉“惰性特征”
python·机器学习·scikit-learn
Freak嵌入式11 小时前
MCU 低功耗模式解析:时钟门控、电源门控、深度休眠
人工智能·python·单片机·嵌入式硬件·开源·依赖倒置原则·micropython
weixin_BYSJ198712 小时前
springboot校园自习室管理小程序---附源码32142
java·javascript·spring boot·python·django·flask·php
用户83562907805113 小时前
使用 Python 在 PDF 中绘制线条、矩形和自定义图形
后端·python