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
相关推荐
lipku1 小时前
数字人直播开源项目LiveStream
python·开源·数字人·数字人直播
阿童木写作2 小时前
Python实现亚马逊商品图批量智能抠图教程
人工智能·python
axinawang2 小时前
第24课:while循环的应用
python
三亚兴嘉装饰2 小时前
三亚服装店装修
python
小柯南敲键盘3 小时前
速卖通AI图片翻译API集成实战
人工智能·python
tqs_123453 小时前
Agent智能体+Skill插件引擎+Milvus混合检索 技术沉淀
java·python·milvus
眼泪划过的星空4 小时前
LangChain 两大基础提示词模板:PromptTemplate 与 ChatPromptTemplate 详解
人工智能·python·langchain
狗都不学爬虫_4 小时前
AI逆向 - 99aq中心滑块验证+登录(wasm纯算)
爬虫·python·网络爬虫
天才测试猿4 小时前
实例介绍:Unittest框架及自动化测试实现流程
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
veminhe5 小时前
元数据索引有关的错
人工智能·python