-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphSearchEngineImpl.java
More file actions
81 lines (69 loc) · 2.2 KB
/
GraphSearchEngineImpl.java
File metadata and controls
81 lines (69 loc) · 2.2 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import java.io.*;
import java.util.*;
import java.util.stream.*;
import java.util.function.*;
/**
* Implements the GraphSearchEngine interface.
*/
public class GraphSearchEngineImpl implements GraphSearchEngine {
private HashMap<Node, Node> visited; // keeps track of the nodes visited
private ArrayList<Node> lookAtNeighbors; // keeps track of the nodes to visit (its a queue)
public GraphSearchEngineImpl() {
visited = new HashMap<>();
lookAtNeighbors = new ArrayList<>();
}
/*
* creates the shortest path between two nodes
* @param start is the starting node, end is the ending node
*/
public List<Node> findShortestPath(Node start, Node end) {
// checks if starting or ending nodes are valid nodes
if (start == null || end == null) {
return null;
}
if (start.equals(end)) {
return makeCorrectRoute(visited, end, start);
} else {
addToLookAtNeighbors(start, visited, lookAtNeighbors);
while (!lookAtNeighbors.isEmpty()) {
Node current = lookAtNeighbors.get(0);
if (current.equals(end)) {
return makeCorrectRoute(visited, end, start);
} else {
addToLookAtNeighbors(current, visited, lookAtNeighbors);
}
lookAtNeighbors.remove(0);
}
}
return null;
}
/*
* adds to the array list lookAtNeighbors
* @param start is the node to get the neighbors from
* visited is the hash map of visited nodes
* lookAtNeighbors is the queue of nodes to look through
*/
public void addToLookAtNeighbors(Node start, HashMap<Node, Node> visited, ArrayList<Node> lookAtNeighbors) {
for (Node neighbor : start.getNeighbors()) {
if (!visited.containsKey(neighbor)) {
lookAtNeighbors.add(neighbor);
visited.put(neighbor, start);
}
}
}
/*
* builds the correct path from the list of visited map
* @param visited is a map of all visited nodes end is the ending node start is
* the starting node
*/
public ArrayList<Node> makeCorrectRoute(HashMap<Node, Node> visited, Node end, Node start) {
ArrayList<Node> path = new ArrayList<>();
Node current = end;
path.add(0, current);
while (current != null && !current.equals(start)) {
current = visited.get(current);
path.add(0, current);
}
return path;
}
}