Find if Path Exists in Graph Visualizer & Step-by-Step Algorithm Solution

Determine if a valid path exists between a source vertex and destination vertex in a bi-directional graph using Depth-First Search (DFS) with visited state tracking.

Category: graphs | Difficulty: Easy

Tags: Graph, DFS, BFS, Union-Find, Connectivity

Find if Path Exists in Graph

Drag nodes to arrange
GRAPH CONNECTIVITY (3 VERTICES)
0
SRC: start
1
2
DST: goal
VISITED VERTICES
(Empty Set)
100%
state
source0
destination2
current-
visitedCount0/3
Initialization
1/15
Explanation

Checking if a valid path exists from source vertex 0 to destination vertex 2 among 3 vertices.

Source Code
1function validPath(n, edges, source, destination) {
2 const adjacency = Array.from({ length: n }, () => []);
3 const visited = Array(n).fill(false);
4 for (const [u, v] of edges) {
5 adjacency[u].push(v);
6 adjacency[v].push(u);
7 }
8 function dfs(node) {
9 if (node === destination) return true;
10 visited[node] = true;
11 for (const neighbour of adjacency[node]) {
12 if (!visited[neighbour] && dfs(neighbour)) return true;
13 }
14 return false;
15 }
16 return dfs(source);
17}