当前位置: 首页 > article >正文

leetcode1971.寻找图中是否存在路径

 初尝并查集,直接套用模板

class Solution {
private:
    vector<int> father;

    void init() {
        for(int i=0;i<father.size();i++)
            father[i]=i;
    }

    int find(int v) {
        return v==father[v]?v:father[v]=find(father[v]);//路径压缩
    }

    bool isSame(int u,int v){
        u=find(u);
        v=find(v);
        return u==v;
    }

    //将v->u这条边加入到并查集中
    void join(int u,int v) {
        u=find(u);
        v=find(v);
        if(u==v) 
            return;
        else
            father[v]=u;
    }
public:
    bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
        father=vector<int>(n);
        this->init();
        for(int i=0;i<edges.size();i++){
            int u=edges[i][0];
            int v=edges[i][1];
            this->join(u,v);
        }
        return this->isSame(source,destination);
    }
};

 


http://www.kler.cn/a/597480.html

相关文章:

  • List附加对象
  • Jenkins显示pytest单元测试报告无样式问题解决
  • 塔能智慧运维箱:智慧城市的“量子跃迁”,创新与售后的双轨驱动
  • SpringBoot3实战(SpringBoot3+Vue3基本增删改查、前后端通信交互、配置后端跨域请求、数据批量删除(超详细))(3)
  • Java 填充 PDF 模版
  • 系统架构书单推荐(一)领域驱动设计与面向对象
  • 《AI大模型趣味实战》第6集:基于大模型和RSS聚合打造个人新闻电台(桌面版)
  • DHCP详解
  • mysql如何给字段添加默认值?
  • DAgent:自动化报告生成智能体方案
  • Git push后撤销提交
  • centos7搭建postgresql12主从
  • [贪心算法]最长回文串 增减字符串匹配 分发饼干
  • S32K144入门笔记(十七):PDB的API函数解读
  • C++20 中线程管理与取消机制的深度剖析
  • C++ 面向对象程序设计 - 学习笔记(持续更新中)
  • 第十三章 : Names in Templates_《C++ Templates》notes
  • debian安装Open5GS
  • 场外个股期权是什么?场外个股期权还能做吗?
  • 论文阅读:2023 arxiv Provable Robust Watermarking for AI-Generated Text