LeetCode 1971.寻找图中是否存在路径

题目

有一个具有 n 个顶点的 双向 图,其中每个顶点标记从 0n - 1(包含 0n - 1)。图中的边用一个二维整数数组 edges 表示,其中 edges[i] = [ui, vi] 表示顶点 ui 和顶点 vi 之间的双向边。 每个顶点对由 最多一条 边连接,并且没有顶点存在与自身相连的边。

请你确定是否存在从顶点 source 开始,到顶点 destination 结束的 有效路径

给你数组 edges 和整数 nsourcedestination,如果从 sourcedestination 存在 有效路径 ,则返回 true,否则返回 false

思路:先构建邻接表,再dfs遍历

代码

java 复制代码
class Solution {
    public boolean validPath(int n, int[][] edges, int source, int destination) {
        List<Integer>[] g = new ArrayList[n];
        for (int i = 0; i < n; i++) {
            g[i] = new ArrayList<>();
        } 
        for (int[] edge : edges) {
            int x = edge[0];
            int y = edge[1];
            g[x].add(y);
            g[y].add(x);
        }
        boolean[] isVisit = new boolean[n];
        boolean ans = dfs(g, isVisit, source, destination);
        return ans;
    }

    private boolean dfs(List<Integer>[] g, boolean[] isVisit, int cur, int destination) {
        if (cur == destination) {
            return true;
        }
        isVisit[cur] = true;
        for (int y : g[cur]) {
            if (!isVisit[y]) {
                if (dfs(g, isVisit, y, destination)) {
                    return true;
                }
            }
        }
        return false;
    }
}

性能

相关推荐
AbandonForce17 分钟前
简谈线程池
开发语言·c++·算法
智购科技智能售货柜28 分钟前
2026自动售货机商品掉落声学计数方案:从麦克风到频谱识别的工程实践~YH
人工智能·算法
leo_messi9441 分钟前
面试知识点梳理及相关面试题(十六)-- 分布式设计
分布式·面试·职场和发展
土司大王41 分钟前
LeetCode hot100——实现 Trie (前缀树)
java·算法·leetcode
水龙吟啸1 小时前
华为研发岗AI方向9.9机考题复盘&分析
人工智能·python·算法·华为
小七在进步1 小时前
类和对象(一)
java·数据结构·算法
Y_Bk1 小时前
2026 ICPC EC网络预选赛第一场
算法
CarIise1 小时前
C语言字符串基础:从char数组到双指针反转算法
算法
佳児素花痴╮1 小时前
C++速通2
开发语言·c++·算法
麻瓜code1 小时前
【LeetCode】相交链表:双指针法,一次遍历找到交点
算法·leetcode·链表