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
相关推荐
珺毅同学6 小时前
YOLO生成预测json标签迁移问题
python·yolo·json
骑士雄师6 小时前
18.4 长期记忆可修改版
python
~小先生~7 小时前
Python从入门到放弃(一)
开发语言·python
天佑木枫7 小时前
第2天:变量与数据类型 —— 让程序记住信息
python
Dust-Chasing8 小时前
Claude Code源码剖析 - Claude Code 上下文压缩机制
人工智能·python·ai
Cloud_Shy6189 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 33 - 35)
开发语言·人工智能·笔记·python·学习方法
abcy07121310 小时前
python pandas csv异步后台清洗前端优先返回成功信息
前端·python·pandas
颜酱10 小时前
LangChain使用RAG 入门:让大模型读懂你的私有文档
python·langchain
天天进步201510 小时前
Python全栈项目--校园智能宿舍管理系统
开发语言·python
测试员周周11 小时前
【AI测试智能体-面试】AI测试面试60题(附回答思路)
人工智能·python·功能测试·测试工具·单元测试·自动化·测试用例