DEV Community

Karleb
Karleb

Posted on

#1971. Find if Path Exists in Graph

https://leetcode.com/problems/find-if-path-exists-in-graph/description/?envType=daily-question&envId=2024-04-22

function hasPath(graph, src, dest, visited) {
    visited[src] = true;

    if (src === dest)
        return true;

    for (let neighbor of graph[src]) {
        if (!visited[neighbor]) {
            if (hasPath(graph, neighbor, dest, visited))
                return true;
        }
    }

    return false;
}

function validPath(n, edges, start, end) {
    const graph = Array.from({ length: n }, () => []);

    for (let [u, v] of edges) {
        graph[u].push(v);
        graph[v].push(u);
    }

    const visited = Array(n).fill(false);

    return hasPath(graph, start, end, visited);
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)