File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed
src/main/java/com/thealgorithms/backtracking Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .*;
2+
3+ class Solution {
4+ // Function to perform DFS traversal
5+ public void dfs (int v , List <Integer >[] adj ,
6+ boolean [] visited ,
7+ List <Integer > result ) {
8+
9+ // Mark current node as visited
10+ visited [v ] = true ;
11+
12+ // Store node in result
13+ result .add (v );
14+
15+ // Traverse all neighbours
16+ for (int u : adj [v ]) {
17+ if (!visited [u ]) {
18+ dfs (u , adj , visited , result );
19+ }
20+ }
21+ }
22+ }
23+
24+ public class Main {
25+ public static void main (String [] args ) {
26+ // Number of vertices
27+ int V = 5 ;
28+
29+ // Adjacency list
30+ List <Integer >[] adj = new ArrayList [V ];
31+ for (int i = 0 ; i < V ; i ++) {
32+ adj [i ] = new ArrayList <>();
33+ }
34+ adj [0 ].addAll (Arrays .asList (1 , 2 ));
35+ adj [1 ].addAll (Arrays .asList (0 , 3 ));
36+ adj [2 ].addAll (Arrays .asList (0 , 4 ));
37+ adj [3 ].add (1 );
38+ adj [4 ].add (2 );
39+
40+ // Visited array
41+ boolean [] visited = new boolean [V ];
42+
43+ // Result list
44+ List <Integer > result = new ArrayList <>();
45+
46+ // Create object
47+ Solution sol = new Solution ();
48+
49+ // Run DFS from node 0
50+ sol .dfs (0 , adj , visited , result );
51+
52+ // Print traversal
53+ for (int x : result ) {
54+ System .out .print (x + " " );
55+ }
56+ System .out .println ();
57+ }
58+ }
You can’t perform that action at this time.
0 commit comments