1
+ /*
2
+ If there was a cycle, like if there was a path from one
3
+ vertex to itself, we would be stuck in an infinite loop, continuously
4
+ iterating over the same neighbors. To account for this, we can use an
5
+ ArrayList to keep track of all the vertices that we have visited.
6
+ */
7
+
8
+ // USE GRAPH FILE FROM GRAPH FOLDER
9
+
10
+ import java .util .ArrayList ;
11
+
12
+ class GraphTraverser {
13
+ public static void depthFirstTraversal (Vertex start , ArrayList <Vertex > visitedVertices ) {
14
+ System .out .println (start .getData ());
15
+
16
+ if (start .getEdges ().size () > 0 ) {
17
+ Vertex neighbor = start .getEdges ().get (0 ).getEnd ();
18
+
19
+ if (!visitedVertices .contains (neighbor )) {
20
+ visitedVertices .add (neighbor );
21
+ GraphTraverser .depthFirstTraversal (neighbor , visitedVertices );
22
+ }
23
+ }
24
+ }
25
+
26
+ // USE TO TEST THE GRAPH
27
+ class TestGraph {
28
+ private Graph testGraph ;
29
+
30
+ public TestGraph () {
31
+ this .testGraph = new Graph (false , true );
32
+ Vertex startNode = testGraph .addVertex ("v0.0.0" );
33
+ Vertex v1 = this .testGraph .addVertex ("v1.0.0" );
34
+ Vertex v2 = this .testGraph .addVertex ("v2.0.0" );
35
+
36
+ Vertex v11 = this .testGraph .addVertex ("v1.1.0" );
37
+ Vertex v12 = this .testGraph .addVertex ("v1.2.0" );
38
+ Vertex v21 = this .testGraph .addVertex ("v2.1.0" );
39
+
40
+ Vertex v111 = this .testGraph .addVertex ("v1.1.1" );
41
+ Vertex v112 = this .testGraph .addVertex ("v1.1.2" );
42
+ Vertex v121 = this .testGraph .addVertex ("v1.2.1" );
43
+ Vertex v211 = this .testGraph .addVertex ("v2.1.1" );
44
+
45
+ this .testGraph .addEdge (startNode , v1 , null );
46
+ this .testGraph .addEdge (startNode , v2 , null );
47
+
48
+ this .testGraph .addEdge (v1 , v11 , null );
49
+ this .testGraph .addEdge (v1 , v12 , null );
50
+ this .testGraph .addEdge (v2 , v21 , null );
51
+
52
+ this .testGraph .addEdge (v11 , v111 , null );
53
+ this .testGraph .addEdge (v11 , v112 , null );
54
+ this .testGraph .addEdge (v12 , v121 , null );
55
+ this .testGraph .addEdge (v21 , v211 , null );
56
+
57
+ // create a cycle
58
+ this .testGraph .addEdge (v211 , v2 , null );
59
+ }
60
+
61
+ public Vertex getStartingVertex () {
62
+ return this .testGraph .getVertices ().get (0 );
63
+ }
64
+ }
65
+
66
+ // MAIN METHOD
67
+ public static void main (String [] args ) {
68
+ TestGraph test = new TestGraph ();
69
+ Vertex startingVertex = test .getStartingVertex ();
70
+ ArrayList <Vertex > visitedVertices = new ArrayList <Vertex >();
71
+ visitedVertices .add (startingVertex );
72
+
73
+ GraphTraverser .depthFirstTraversal (startingVertex , visitedVertices );
74
+ }
75
+ }
0 commit comments