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

性能

相关推荐
黎雁·泠崖2 小时前
栈与队列实战通关:3道经典OJ题深度解析
c语言·数据结构·leetcode
ytttr8738 小时前
隐马尔可夫模型(HMM)MATLAB实现范例
开发语言·算法·matlab
AlenTech9 小时前
160. 相交链表 - 力扣(LeetCode)
数据结构·leetcode·链表
点云SLAM9 小时前
凸优化(Convex Optimization)理论(1)
人工智能·算法·slam·数学原理·凸优化·数值优化理论·机器人应用
jz_ddk9 小时前
[学习] 卫星导航的码相位与载波相位计算
学习·算法·gps·gnss·北斗
放荡不羁的野指针10 小时前
leetcode150题-动态规划
算法·动态规划
sin_hielo10 小时前
leetcode 1161(BFS)
数据结构·算法·leetcode
一起努力啊~10 小时前
算法刷题-二分查找
java·数据结构·算法
水月wwww10 小时前
【算法设计】动态规划
算法·动态规划
零售ERP菜鸟10 小时前
当业务战略摇摆不定:在变化中锚定不变的IT架构之道
信息可视化·职场和发展·架构·创业创新·学习方法·业界资讯