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
相关推荐
geovindu16 分钟前
python: Face Recognition
开发语言·后端·python·人脸识别
2601_9548118230 分钟前
AI科学实验室MHS标准解读:AI智能体如何统一控制实验室设备接口
人工智能·python
一位正在转型AI全栈的前端工程师30 分钟前
AI 全栈学习之旅 -Week 9:什么是AI Agent?从Function Calling到LangGraph
前端·python
用户03321266636732 分钟前
使用 Python 为 PowerPoint 设置背景色和背景图【附代码示例】
python
ever_up9731 小时前
LangChain基础知识概述1
人工智能·python·langchain
asdzx671 小时前
Python 实现 PDF 文本查找与高亮标注
开发语言·python·pdf
zander2581 小时前
LeetCode 1143. 最长公共子序列
开发语言·python·算法
轩情吖2 小时前
Python基础知识点完整总结
python·字符串·编程语言·函数·列表·元组·字典
青 春 记 忆2 小时前
零基础入门python69:为 FastAPI 项目构建可复现 Docker 镜像
python·fastapi·后端开发
<花开花落>2 小时前
Python 项目迁移到 uv:经验小结与可复用工作流
python·uv