-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolver.java
76 lines (65 loc) · 1.86 KB
/
Solver.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package hw7;
import java.util.Iterator;
import edu.princeton.cs.algs4.Graph;
import edu.princeton.cs.algs4.BreadthFirstPaths;
public class Solver {
public static String solve(char[][] grid) {
// TODO
/*
* 1. Construct a graph using grid
* 2. Use BFS to find shortest path from start to finish
* 3. Return the sequence of moves to get from start to finish
*/
int vert = grid.length * grid[0].length;
Graph g = new Graph(vert);
int sint = -1;
int fint = -1;
String fin = "";
for(int row = 0; row < grid.length; row++) {
for(int col = 0; col < grid[row].length; col++) {
int gpos = (row*grid.length)+col;
if(col+1 != grid[row].length && (grid[row][col+1] == ' ' || grid[row][col+1] == 's' || grid[row][col+1] == 'f')) { //check below
g.addEdge(gpos,gpos+1);
}
if(row+1 != grid.length && (grid[row+1][col] == ' ' || grid[row+1][col] == 's' || grid[row+1][col] == 'f')) { //check right
g.addEdge(gpos, gpos+grid.length);
}
if(grid[row][col] == 's') {
sint = gpos;
}
if(grid[row][col] == 'f') {
fint = gpos;
}
}
}
BreadthFirstPaths bfp = new BreadthFirstPaths(g, sint);
String path = "";
if(bfp.hasPathTo(fint)) {
path = bfp.pathTo(fint).toString();
}
else {
return null;
}
String[] p = path.split(" ");
int[] pathar = new int[p.length];
for(int n = 0; n < p.length; n++) {
pathar[n] = Integer.parseInt(p[n]);
}
for(int x = 1; x < pathar.length; x++) {
if(pathar[x-1] + grid.length == pathar[x]) {
fin += "D";
}
else if(pathar[x-1] + 1 == pathar[x]) {
fin += "R";
}
else if(pathar[x-1] - grid.length == pathar[x]) {
fin += "U";
}
else if(pathar[x-1] - 1 == pathar[x]) {
fin += "L";
}
}
// Hardcoded solution to toyTest
return fin;
}
}