Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b1ce94f

Browse files
Added DFS (ALL PATHS)
1 parent d108709 commit b1ce94f

File tree

1 file changed

+71
-0
lines changed
  • Graph Data Structures/Graph Traversal/Depth-First Traversal/Depth-First Traversal (All paths)

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// We will traverse down all the paths (not just the first possible path)
2+
3+
// USE GRAPH FILE FROM GRAPH FOLDER
4+
5+
import java.util.ArrayList;
6+
7+
class GraphTraverser {
8+
public static void depthFirstTraversal(Vertex start, ArrayList<Vertex> visitedVertices) {
9+
System.out.println(start.getData());
10+
11+
for (Edge e: start.getEdges()) {
12+
Vertex neighbor = e.getEnd();
13+
14+
if (!visitedVertices.contains(neighbor)) {
15+
visitedVertices.add(neighbor);
16+
GraphTraverser.depthFirstTraversal(neighbor, visitedVertices);
17+
}
18+
}
19+
}
20+
21+
// USE IT TO TEST GRAPH
22+
class TestGraph {
23+
private Graph testGraph;
24+
25+
public TestGraph() {
26+
this.testGraph = new Graph(false, true);
27+
Vertex startNode = testGraph.addVertex("v0.0.0");
28+
Vertex v1 = this.testGraph.addVertex("v1.0.0");
29+
Vertex v2 = this.testGraph.addVertex("v2.0.0");
30+
31+
Vertex v11 = this.testGraph.addVertex("v1.1.0");
32+
Vertex v12 = this.testGraph.addVertex("v1.2.0");
33+
Vertex v21 = this.testGraph.addVertex("v2.1.0");
34+
35+
Vertex v111 = this.testGraph.addVertex("v1.1.1");
36+
Vertex v112 = this.testGraph.addVertex("v1.1.2");
37+
Vertex v121 = this.testGraph.addVertex("v1.2.1");
38+
Vertex v211 = this.testGraph.addVertex("v2.1.1");
39+
40+
this.testGraph.addEdge(startNode, v1, null);
41+
this.testGraph.addEdge(startNode, v2, null);
42+
43+
this.testGraph.addEdge(v1, v11, null);
44+
this.testGraph.addEdge(v1, v12, null);
45+
this.testGraph.addEdge(v2, v21, null);
46+
47+
this.testGraph.addEdge(v11, v111, null);
48+
this.testGraph.addEdge(v11, v112, null);
49+
this.testGraph.addEdge(v12, v121, null);
50+
this.testGraph.addEdge(v21, v211, null);
51+
52+
// create a cycle
53+
this.testGraph.addEdge(v211, v2, null);
54+
}
55+
56+
public Vertex getStartingVertex() {
57+
return this.testGraph.getVertices().get(0);
58+
}
59+
}
60+
61+
// MAIN METHOD
62+
63+
public static void main(String[] args) {
64+
TestGraph test = new TestGraph();
65+
Vertex startingVertex = test.getStartingVertex();
66+
ArrayList<Vertex> visitedVertices = new ArrayList<Vertex>();
67+
visitedVertices.add(startingVertex);
68+
69+
GraphTraverser.depthFirstTraversal(startingVertex, visitedVertices);
70+
}
71+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /