[力扣题解] 1971. 寻找图中是否存在路径

题目:1971. 寻找图中是否存在路径

思路

并查集

代码

cpp 复制代码
class Solution {
private:
    int n = 200005;
    int father[200005] = {0};
    void init()
    {
        int i;
        for(i = 0; i < n; i++)
        {
            father[i] = i;
        }
    }

    int find(int u)
    {
        if(u == father[u])
        {
            return u;
        }
        else
        {
            return father[u] = find(father[u]);
        }
    }

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

    // 加入 u -> v
    void join(int u, int v)
    {
        u = find(u);
        v = find(v);
        if(u == v)
        {
            return;
        }
        else
        {
            father[u] = v;
        }
    }


public:
    bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
        int i, u, v;
        init();
        for(i = 0; i < edges.size(); i++)
        {
            join(edges[i][0], edges[i][1]);
        }
        return isSame(source, destination);
    }
};

注意数组不要越界了,validPath函数里n是节点个数,edge长度是边的个数,可不一定相等哦!

相关推荐
pystraf12 分钟前
UOJ 228 基础数据结构练习题 Solution
数据结构·c++·算法·线段树
海底火旺21 分钟前
破解二维矩阵搜索难题:从暴力到最优的算法之旅
javascript·算法·面试
黄昏ivi1 小时前
电力系统最小惯性常数解析
算法
独家回忆3642 小时前
每日算法-250425
算法
烁3472 小时前
每日一题(小白)模拟娱乐篇33
java·开发语言·算法
Demons_kirit2 小时前
LeetCode 2799、2840题解
算法·leetcode·职场和发展
软行2 小时前
LeetCode 每日一题 2845. 统计趣味子数组的数目
数据结构·c++·算法·leetcode
永远在Debug的小殿下2 小时前
查找函数【C++】
数据结构·算法
我想进大厂3 小时前
图论---染色法(判断是否为二分图)
数据结构·c++·算法·深度优先·图论
油泼辣子多加3 小时前
【风控】稳定性指标PSI
人工智能·算法·金融