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
相关推荐
JaydenAI3 分钟前
[拆解LangChain执行引擎]支持自然语言查询的长期存储
python·langchain
dreams_dream37 分钟前
Python 的 GIL 是什么?有什么影响?
开发语言·python
小白菜又菜40 分钟前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
python·算法·leetcode
多恩Stone44 分钟前
【3D-AICG 系列-12】Trellis 2 的 Shape VAE 的设计细节 Sparse Residual Autoencoding Layer
人工智能·python·算法·3d·aigc
Loo国昌1 小时前
【AI应用开发实战】09_Prompt工程与模板管理:构建可演进的LLM交互层
大数据·人工智能·后端·python·自然语言处理·prompt
遨游xyz2 小时前
Trie树(字典树)
开发语言·python·mysql
重启编程之路2 小时前
AlphaLens Pro V14.0 商业级量化推演终端 | 功能白皮书
python
二十雨辰2 小时前
[python]-生成器和正则
python
Loo国昌2 小时前
【AI应用开发实战】06_向量存储与EmbeddingProvider设计
人工智能·后端·python·语言模型·自然语言处理·prompt
两万五千个小时2 小时前
构建mini Claude Code:07 - 一切皆文件:持久化任务系统
人工智能·python·架构