-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGreedyGraphSearch.java
More file actions
244 lines (218 loc) · 7.52 KB
/
Copy pathGreedyGraphSearch.java
File metadata and controls
244 lines (218 loc) · 7.52 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import java.io.*;
import java.util.*;
/**
* File: GreedyGraphSearch.java
*
* Author: Jason W Gould
* Descr: GreedyGraphSearch parses a text file and performs greedy (informed)
graph search on the input nodes. See README.txt for instructions
*/
class GreedyGraphSearch
{
private BufferedReader reader;
private HashMap<Integer, Node> nodeList;
private int start_x,
start_y,
goal_x,
goal_y;
private Node startNode = null,
goalNode = null;
public GreedyGraphSearch(int goal_x, int goal_y, int start_x, int start_y)
{
this.goal_x = goal_x;
this.goal_y = goal_y;
this.start_x = start_x;
this.start_y = start_y;
}
// Perform greedy graph search for the goal node
public void start()
{
PriorityQueue<Node> frontier = new PriorityQueue<>();
HashMap<Integer, Node> explored = new HashMap<>();
int count = 0, maxSize = 0;
// Add the start node to the queue
frontier.add(startNode);
while(!frontier.isEmpty())
{
// Get the head node from the queue
Node node = frontier.poll();
// Check if it's the goal node
if(goalNode == node)
{
System.out.println("iter " + count + ":\tchecking: ("
+ node.getVertex_X() + ","
+ node.getVertex_Y() + "),"
+ "\tgoal found!");
traceGoalPath(goalNode, count, maxSize, explored);
return;
}
// Add the node to explored list
explored.put(node.getId(), node);
// Print the status
System.out.println("iter " + count + ":\tchecking: ("
+ node.getVertex_X() + ","
+ node.getVertex_Y() + "), "
+ "\tfrontier size = " + frontier.size());
// Add each of the successors to the frontier if they are not already explored
for (Node n : node.successor())
{
if (!explored.containsKey(n.getId()) && !frontier.contains(n))
{
n.setParent(node);
frontier.add(n);
}
}
count++;
if (maxSize < frontier.size())
{
maxSize = frontier.size();
}
}
System.out.println("failure.");
}
// Determines the output path
private void traceGoalPath(Node goal, int count, int maxSize, HashMap explored)
{
Stack<String> path = new Stack<>();
System.out.println("\nsolution path:");
path.add( " vertex (" + goal.getVertex_X() + ", "
+ goal.getVertex_Y() + ")");
int length = 0;
Node parent = goal.getParent();
while(parent != null)
{
path.push(" vertex (" + parent.getVertex_X() + ", " + parent.getVertex_Y() + ")");
parent = parent.getParent();
length++;
}
while(!path.isEmpty())
{
System.out.println(path.pop());
}
System.out.println("\ntotal iterations = " + count);
System.out.println("max frontier size = " + maxSize);
System.out.println("vertices visited = " + explored.size());
System.out.println("path length = " + length);
}
// Parse the input file (graph adjacency list format)
public HashMap<Integer, Node> parseGraph(String fileName)
{
loadInputFile(fileName);
nodeList = new HashMap<>(); // to hold the parsed Nodes
try
{
String inputLine = null;
// Read in each line of the input file
while ((inputLine = reader.readLine()) != null)
{
Scanner entry = new Scanner(inputLine);
String identifier = null;
if (entry.hasNext())
{
identifier = entry.next();
// Process the Vertex entries
if (identifier.equals("v"))
{
Node node = parseNode(entry);
nodeList.put(node.getId(), node);
}
// Process the Edge entries
else if (identifier.equals("e"))
{
parseEdge(entry);
}
}
}
reader.close();
if (startNode == null || goalNode == null)
{
throw new Exception("Bad start or goal node coordinates.");
}
} catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
return nodeList;
}
// Parse an individual node entry
private Node parseNode(Scanner entry)
{
Integer id = null, x_coord = null, y_coord = null;
Node newNode = null;
// Get the rest of the Vertex arguments
if (entry.hasNext())
{
id = entry.nextInt();
x_coord = entry.nextInt();
y_coord = entry.nextInt();
newNode = new Node(new Vertex(id, x_coord, y_coord), goal_x, goal_y);
// Check if the coordinates match either start or goal node coords
if (x_coord == start_x && y_coord == start_y)
{
startNode = newNode;
}
if (x_coord == goal_x && y_coord == goal_y)
{
goalNode = newNode;
}
}
return newNode;
}
// Parses edge entries. Adds edges to the specified vertex's successor list
private void parseEdge(Scanner entry)
{
// Get the initial node id
if (entry.hasNext())
{
int nodeID = entry.nextInt();
// If a node with the given id exists:
if (nodeList.containsKey(nodeID))
{
// Get the initial node
Node node = nodeList.get(nodeID);
// Add the successors to the node
while (entry.hasNext())
{
// Read the given node id
int edgeNodeID = entry.nextInt();
// Get the node from id number
if (nodeList.containsKey(edgeNodeID))
{
Node edgeNode = nodeList.get(edgeNodeID);
node.addSuccessor(edgeNode);
} else
{
throw new NoSuchElementException("Edge node "
+ edgeNodeID + " does not exist!");
}
}
} else
{
throw new NoSuchElementException("Node " + nodeID
+ " does not exist!");
}
} else
{
throw new NoSuchElementException("Input Format Error");
}
}
// Loads a new Buffered Reader using the input file string
private void loadInputFile(String fileName)
{
try
{
reader = new BufferedReader(new FileReader(fileName));
System.out.println("Valid input file: " + fileName);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}