-
Notifications
You must be signed in to change notification settings - Fork 0
/
DepthFirstSearch.java
56 lines (53 loc) · 1.61 KB
/
DepthFirstSearch.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.*;
/**
* class that implements depth first search algorithm that finds a path given start vertex
* @author Dana Curca, dcurca, 250976773
*
*/
public class DepthFirstSearch {
//initialize instance variables
RouteGraph inputGraph;
Stack<Intersection> stack;
public DepthFirstSearch(RouteGraph graph) {
stack = new Stack<Intersection>();
inputGraph = graph;
}
/**
* creates a stack and returns it with the necessary paths
*/
public Stack<Intersection> path(Intersection startVertex, Intersection endVertex) throws GraphException {
Stack<Intersection> newStack = new Stack<Intersection>();
pathRec(startVertex, endVertex);
return newStack;
}
/**
* implements depth first search algorithm to find paths
*/
public boolean pathRec(Intersection startVertex, Intersection endVertex) throws GraphException {
startVertex.setMark(true);
stack.push(startVertex);
if(startVertex.getLabel() == endVertex.getLabel()) {
return true; }
//checks to make sure there is a next intersection
else {
Iterator<Road> edges = inputGraph.incidentRoads(startVertex);
while(edges.hasNext()) {
Road road = edges.next();
if(!road.getFirstEndpoint().getMark()) {
//checks the undirected edge whether it is the second endpoint
if(pathRec(road.getFirstEndpoint(), endVertex)) {
return true;
}
}
else if(!road.getFirstEndpoint().getMark()) {
//or if it is the first endpoint
if (pathRec(road.getSecondEndpoint(),endVertex)) {
return true;
}
}
}
stack.pop();
return false;
}
}
}