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
相关推荐
ZHW_AI课题组13 小时前
调用智谱AI实现特定角色扮演对话
python
nexustech13 小时前
simplejson:Python JSON 处理的备用引擎
开发语言·python·其他·json
lulu121654407813 小时前
OpenAI 如何用开源前端生态为 GPT-5.6 铺路? - 微元算力(weytoken)
java·前端·人工智能·python·gpt·开源·ai编程
CC数学建模13 小时前
2026年第十六届APMCM 亚太地区大学生数学建模竞赛(中文赛项)赛题A题:自来水厂水质预测与评估完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模
天天进步201514 小时前
Python全栈项目--基于机器学习的异常检测系统
开发语言·python·机器学习
xxie12379421 小时前
return与print
开发语言·python
秋921 小时前
从 Python 后端工程师转型 AI Engineer(AI 工程化)的完整补课清单(2026实战版)
开发语言·人工智能·python
慕木沐1 天前
Google ADK Java 1.0版本 核心机制与实战 Demo
java·开发语言·python
Tbisnic1 天前
AI大模型学习第十一天:技术选型、安全防护与金融实战
python·学习·ai·大模型·提示词工程
hboot1 天前
AI工程师第一课 - Python
前端·后端·python