Adj List Graph DFS

Run Settings
LanguageJavaScript
Language Version
Run Command
class Solution { DFSUtil(i, adj, visited, res) { if (visited.has(i)) return; res.push(i); visited.add(i); for (let neighbor of adj[i]) { if (!visited.has(neighbor)) { this.DFSUtil(neighbor, adj, visited, res); } } } dfsOfGraph(V, adj) { let visited = new Set(); let res = []; for (let i = 0; i < V; i++) { if (!visited.has(i)) { this.DFSUtil(i, adj, visited, res); } } return res; } } // Test Input let V = 5; let adj = [ [2, 3, 1], [0], [0, 4], [0], [2] ]; let obj = new Solution(); let ans = obj.dfsOfGraph(V, adj); console.log(ans); // Output the result
Editor Settings
Theme
Key bindings
Full width
Lines