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

题目:

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

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

给你数组 edges 和整数 n、source 和 destination,如果从 source 到 destination 存在 有效路径 ,则返回 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;
    }
}

性能:

相关推荐
企业数字化笔记2 小时前
AI视频增强后画质怎么验收?插值基线、伪细节与帧间闪烁的检查方法
人工智能·算法·音视频
学逆向的3 小时前
C 内存属性
c语言·开发语言·算法·网络安全
lengxuenong3 小时前
树状数组 · 信息学学习手册1-求和3个模板
c++·学习·算法·青少年编程
zhangminghuan3 小时前
前端面试应对技巧
前端·面试·职场和发展
ComputerInBook3 小时前
泛函分析概观
人工智能·算法·机器学习·泛函分析
Nuanyt3 小时前
LeetCode Hot100 刷题笔记 · 普通数组专题
java·笔记·算法·leetcode
q27551300423 小时前
AS8132 DP转HDMI 4K60(420)被动式 国产性价比AS方案
linux·算法·硬件架构·dash
安全指北针4 小时前
密态计算:数据 “可用不可见” 的底层技术解析
人工智能·算法
Jmyd01234 小时前
3D 扫描仪选型技术拆解:精度、点云与软件链路
人工智能·算法·3d·三维数字化