import java.io.*; import java.util.*; class Graph{ private int V; private LinkedList<Integer>[] adj; Graph(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList<>(); } void addEdge(int u, int v) { adj[u].add(v); } void calc(int v, boolean vis[]) { vis[v] = true; System.out.print(v + " "); Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!vis[n]) calc(n, vis); } } void DFS(int v) { boolean vis[] = new boolean[V]; calc(v, vis); } public static void main(String args[]) { Graph g = new Graph(8); g.addEdge(0, 1); g.addEdge(3, 2); g.addEdge(5, 2); g.addEdge(3, 5); g.addEdge(3, 4); g.addEdge(4, 6); g.addEdge(6, 3); g.addEdge(6, 7); g.addEdge(7, 1); System.out.print("DFS traversal from vertex 3 is: "); g.DFS(3); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter