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

性能

相关推荐
TracyCoder12314 小时前
LeetCode Hot100(15/100)——54. 螺旋矩阵
算法·leetcode·矩阵
u01092727115 小时前
C++中的策略模式变体
开发语言·c++·算法
2501_9418372615 小时前
停车场车辆检测与识别系统-YOLOv26算法改进与应用分析
算法·yolo
六义义16 小时前
java基础十二
java·数据结构·算法
四维碎片16 小时前
QSettings + INI 笔记
笔记·qt·算法
Tansmjs16 小时前
C++与GPU计算(CUDA)
开发语言·c++·算法
独自破碎E17 小时前
【优先级队列】主持人调度(二)
算法
weixin_4454766817 小时前
leetCode每日一题——边反转的最小成本
算法·leetcode·职场和发展
打工的小王17 小时前
LeetCode Hot100(一)二分查找
算法·leetcode·职场和发展
Swift社区18 小时前
LeetCode 385 迷你语法分析器
算法·leetcode·职场和发展