#1971. Find if Path Exists in Graph

RMAG news

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

Leave a Reply

Your email address will not be published. Required fields are marked *