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;
    }
}

性能

相关推荐
数模竞赛Paid answer3 小时前
2026年中青杯数学建模A题数学建模论文智能评估系统与多智能体优化方法求解全过程论文及程序
算法·数学建模·中青杯
银-豆豆3 小时前
数据结构与算法-动态规划、回溯与贪心
算法·动态规划
JL154 小时前
面试项目被问到自闭-如何把课设包装成亮眼项目
面试·职场和发展
想吃火锅10055 小时前
【leetcode】200. 岛屿数量
算法·leetcode·职场和发展
Nil2086 小时前
leetcode 54螺旋矩阵
算法·leetcode·矩阵
依然鸣6 小时前
PTA团体程序设计天梯赛L1真题讲解L1-077-080
开发语言·c++·算法·深度优先·pat考试·图论
qeen879 小时前
【数据结构】自平衡二叉搜索树各种旋转算法原理解析及AVL树的C++实现
数据结构·c++·算法
lucas_AI9 小时前
1.2B 小模型赢过 235B 大模型:NaviDC-OCR 把文档解析卷明白了
人工智能·深度学习·算法
冻柠檬飞冰走茶10 小时前
PTA基础编程题目集 7-35有理数均值(C++语言实现)
开发语言·数据结构·c++·算法·均值算法