Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.82 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.util.Scanner;
  4.  
  5. import edu.princeton.cs.algs4.Graph;
  6. import edu.princeton.cs.algs4.BreadthFirstPaths;
  7.  
  8. import java.util.ArrayList;
  9.  
  10.  
  11. public class MazeSolver {
  12.  
  13. //private static int numMoves = 0; // Allows us to keep track of how many recursive calls to findPath are required to solve the maze.
  14. private String[][] maze;
  15. int numRows;
  16. int numCols;
  17.  
  18. int numV = 0; //number of vertices/number of periods, O
  19. Graph graph;
  20.  
  21. int sVertex = 0;
  22. int sRow = 0;
  23. int sCol = 0;
  24. int gVertex = 0;
  25.  
  26.  
  27.  
  28. /**
  29. * Creates a 2D array of String, maze Precondition: mazeStr must begin with
  30. * the number of rows followed by a space, the the number of columns
  31. * followed by a space, and finally by a string representation of the maze,
  32. * with rows separated by the newline "\n". The maze string will contain one
  33. * "S", one "G", a "." for each open cell, and a "#" for each obstacle.
  34. *
  35. * @param mazeStr a string meeting the preconditions described above
  36. */
  37. public MazeSolver(String mazeStr) {
  38. int i = 0;
  39. int endIndex = mazeStr.indexOf(" ");
  40. this.numRows = Integer.parseInt(mazeStr.substring(i, endIndex));
  41. i = endIndex + 1;
  42. endIndex = mazeStr.indexOf(" ", i);
  43. this.numCols = Integer.parseInt(mazeStr.substring(i, endIndex));
  44. i = endIndex + 1; // i now points to the first char in first row of maze
  45.  
  46. // Let's make sure our string maze has the proper number of characters in it...
  47. if (numRows * numCols != mazeStr.substring(i).length() - numRows + 1) {
  48. throw new IllegalArgumentException("mazeStr is not well-formed.");
  49. }
  50.  
  51. // Now we build the maze from the maze string.
  52. this.maze = new String[numRows][numCols]; // DON'T FORGET to actually create the array!
  53. for (int row = 0; row < numRows; row++) {
  54. for (int col = 0; col < numCols; col++) {
  55. String val = mazeStr.substring(i, i + 1);
  56. if (val.equals(".") || val.equals("S") || val.equals("G")) numV++;
  57. maze[row][col] = val;
  58. i++;
  59. }
  60. i++; // this increment, after each row, skips the newline character '\n'
  61. }
  62. }
  63.  
  64. /**
  65. * This helper method allows one to create a maze in a text editor. It
  66. * creates a string formed for use by the MazeSolver constructor.
  67. *
  68. * @param fName the name of a text file containing a maze
  69. * @return The maze string in the form of
  70. * "<numRows><space><numCols><space><line1>\n<line2>\n...<lastLine>"
  71. */
  72. public static String makeMazeStringFromFile(String fName) {
  73. String str = "";
  74. // build the mazeStr
  75. //String mazeStr = "" + rows + " " + cols + " ";
  76. // read the text file containing maze characters and append to mazeStr
  77. File file = new File(fName);
  78. Scanner reader = new Scanner(System.in);
  79. try {
  80. reader = new Scanner(file);
  81. } catch (FileNotFoundException e) {
  82. System.out.println("Maze file not found.");
  83. }
  84. String line1 = reader.nextLine();
  85. str = str + line1 + "\n";
  86. int numCols = line1.length();
  87. int numRows = 1;
  88. while (reader.hasNext()) {
  89. String line = reader.nextLine();
  90. str = str + line + "\n";
  91. if (line.length() > 0) {
  92. numRows++;
  93. }
  94. }
  95.  
  96. String mazeStr = "" + numRows + " " + numCols + " " + str.substring(0, str.length());
  97. if (mazeStr.substring(mazeStr.length() - 1).equals("\n")) // did they press ENTER after the last line?
  98. {
  99. mazeStr = mazeStr.substring(0, mazeStr.length() - 1); // drops the last "\n" character
  100. }
  101. reader.close();
  102. return mazeStr;
  103. }
  104.  
  105. /**
  106. * Creates a 2D matrix view of the contents of the array maze
  107. * @return the contents of maze with rows separated by newline '\n'
  108. */
  109. @Override
  110. public String toString() {
  111. String str = "";
  112. for (String[] row : maze) {
  113. for (String val : row) {
  114. str += val;
  115. }
  116. str += "\n";
  117. }
  118. return str;
  119. }
  120.  
  121. public void solve () {
  122. createGraph();
  123. runBFS();
  124. }
  125.  
  126. public void createGraph() {
  127. graph = new Graph(numV);
  128.  
  129. int v = -1;
  130.  
  131. for (int row = 0; row < numRows; row++) {
  132. for (int col = 0; col < numCols; col++) {
  133.  
  134. if (isVertex(maze[row][col])) {
  135. v++;
  136.  
  137. if (maze[row][col].equals("S")) {
  138. sRow = row;
  139. sCol = col;
  140. sVertex = v;
  141. }
  142. else if (maze[row][col].equals("G"))
  143. gVertex = v;
  144.  
  145. if (row > 0 && isVertex(maze[row - 1][col ])) //check up
  146. if (!adjContains( v, (v - verticesBetween(row - 1, col, row, col))))
  147. graph.addEdge(v, (v - verticesBetween(row - 1, col, row, col)));
  148.  
  149. if (col < numCols - 1 && isVertex(maze[row ][col + 1])) //check right
  150. if (!adjContains( v, v + 1))
  151. graph.addEdge(v, v + 1);
  152.  
  153. if (col > 0 && isVertex(maze[row ][col - 1])) //check left
  154. if (!adjContains( v, v - 1))
  155. graph.addEdge(v, v - 1);
  156.  
  157. if (row < numRows - 1 && isVertex(maze[row + 1][col ])) //check down
  158. if (!adjContains( v, (v + verticesBetween(row, col, row + 1, col))))
  159. graph.addEdge(v, (v + verticesBetween(row, col, row + 1, col)));
  160. }
  161. }
  162. }
  163. }
  164.  
  165. //GRAPH METHODS
  166.  
  167. public boolean isVertex (String c) {
  168. if (c.equals(".") || c.equals("S") || c.equals("G")) return true;
  169. else return false;
  170. }
  171.  
  172. public boolean adjContains (int v, int hypV) {
  173. for (int e : graph.adj(v)) {
  174. if (e == hypV) return true;
  175. }
  176. return false;
  177. }
  178.  
  179. public int verticesBetween (int x1, int y1, int x2, int y2) {
  180. int v = 0;
  181.  
  182. int colSet = y1;
  183.  
  184. for (int row = x1; row < numRows; row++) {
  185. if (row == x1 + 1) colSet = 0;
  186. for (int col = colSet; col < numCols; col++) {
  187. if (row == x1 && col == y1);
  188. else if (isVertex(maze[row][col]))
  189. v++;
  190. if (row == x2 && col == y2) return v;
  191. }
  192. }
  193. return v;
  194. }
  195.  
  196. //DFS METHODS
  197.  
  198. public void runBFS () {
  199. BreadthFirstPaths BFS = new BreadthFirstPaths(graph, sVertex);
  200. Iterable<Integer> path = BFS.pathTo(gVertex);
  201.  
  202. if (!BFS.hasPathTo(gVertex))
  203. System.out.println("this maze is unsolvable.");
  204. else {
  205. ArrayList<Integer> pathCopy = new ArrayList<Integer>();
  206.  
  207. for (Integer v : path)
  208. pathCopy.add(v);
  209.  
  210. int v = -1;
  211.  
  212. for (int row = 0; row < numRows; row++) {
  213. for (int col = 0; col < numCols; col++) {
  214. if (!maze[row][col].equals("#")) {
  215. v++;
  216. if (maze[row][col].equals("."))
  217. if (pathCopy.contains(v))
  218. maze[row][col] = "+";
  219. }
  220. }
  221. }
  222. }
  223. }
  224.  
  225. public void printWithColor () {
  226. final String ANSI_RESET = "\u001B[0m";
  227. final String ANSI_PURPLE = "\u001B[35m";
  228.  
  229. for (int row = 0; row < numRows; row++) {
  230. for (int col = 0; col < numCols; col++) {
  231. String c = maze[row][col];
  232. if (c.equals("+"))
  233. System.out.print(ANSI_PURPLE + "+" + ANSI_RESET);
  234. else
  235. System.out.print(c);
  236. }
  237. System.out.println();
  238. }
  239. }
  240.  
  241. /**
  242. * @param args the command line arguments
  243. */
  244. public static void main (String[] args) throws FileNotFoundException {
  245. MazeSolver ms = new MazeSolver("6 6 ##S###\n#....#\n#....#\n#....#\n#..#.#\n#G####");
  246. System.out.println(ms);
  247. ms.solve();
  248. System.out.println(ms);
  249.  
  250. /*System.out.println("\nSolving maze in maze0.txt");
  251. ms = new MazeSolver(makeMazeStringFromFile("maze0.txt"));
  252. System.out.println(ms);
  253. ms.solve();
  254. System.out.println(ms);*/
  255.  
  256. System.out.println("\nSolving maze in maze1.txt");
  257. ms = new MazeSolver(makeMazeStringFromFile("maze1.txt"));
  258. System.out.println(ms);
  259. ms.solve();
  260. System.out.println(ms);
  261.  
  262. System.out.println("\nSolving maze in maze2.txt");
  263. ms = new MazeSolver(makeMazeStringFromFile("maze2.txt"));
  264. System.out.println(ms);
  265. ms.solve();
  266. System.out.println(ms);
  267.  
  268. System.out.println("\nSolving maze in maze3.txt");
  269. ms = new MazeSolver(makeMazeStringFromFile("maze3.txt"));
  270. System.out.println(ms);
  271. ms.solve();
  272. System.out.println(ms);
  273.  
  274. System.out.println("\nSolving maze in maze4.txt");
  275. ms = new MazeSolver(makeMazeStringFromFile("maze4NoSolution.txt"));
  276. System.out.println(ms);
  277. ms.solve();
  278. System.out.println(ms);
  279. }
  280. }
  281.  
  282. //comment of sample main() runs
  283.  
  284. /*
  285. ##S###
  286. #....#
  287. #....#
  288. #....#
  289. #..#.#
  290. #G####
  291.  
  292. ##S###
  293. #.+..#
  294. #.+..#
  295. #.+..#
  296. #++#.#
  297. #G####
  298.  
  299.  
  300. Solving maze in maze1.txt
  301. ####################
  302. #.................##
  303. #..................#
  304. S..................#
  305. ##################.#
  306. G...#..............#
  307. ###.#..............#
  308. ###................#
  309. ###...............##
  310. ##................##
  311. ##.#################
  312. ##..################
  313. ###.################
  314. ###.#..............#
  315. ###.########.#######
  316. #.................##
  317. #.................##
  318. ##...............###
  319. ##................##
  320. ####################
  321.  
  322. ####################
  323. #.................##
  324. #..................#
  325. S++++++++++++++++++#
  326. ##################+#
  327. G+++#.............+#
  328. ###+#.............+#
  329. ###++++++++++++++++#
  330. ###...............##
  331. ##................##
  332. ##.#################
  333. ##..################
  334. ###.################
  335. ###.#..............#
  336. ###.########.#######
  337. #.................##
  338. #.................##
  339. ##...............###
  340. ##................##
  341. ####################
  342.  
  343.  
  344. Solving maze in maze2.txt
  345. ####################
  346. #.................##
  347. #..................#
  348. S..................#
  349. ##################.#
  350. #...#..............#
  351. ###.#..............#
  352. ###................#
  353. ###...............##
  354. ##................##
  355. ##.#################
  356. ##..################
  357. ###.################
  358. ##..#..............#
  359. ##.#########.#######
  360. #.................##
  361. #.................##
  362. ##...............###
  363. ##................##
  364. #################G##
  365.  
  366. ####################
  367. #.................##
  368. #..................#
  369. S++++++++++++++++++#
  370. ##################+#
  371. #...#.............+#
  372. ###.#.............+#
  373. ###..............++#
  374. ###..............+##
  375. ##++++++++++++++++##
  376. ##+#################
  377. ##++################
  378. ###+################
  379. ##++#..............#
  380. ##+#########.#######
  381. #.+...............##
  382. #.+...............##
  383. ##+..............###
  384. ##++++++++++++++++##
  385. #################G##
  386.  
  387.  
  388. Solving maze in maze3.txt
  389. ####################
  390. #.................##
  391. #..................#
  392. #..................#
  393. ##################.#
  394. #...#..............#
  395. ###.#..............#
  396. ###................#
  397. ###...............##
  398. ##................##
  399. ##.#################
  400. ##..################
  401. ###.################
  402. ##..#..............#
  403. ##.#########.#######
  404. #.................##
  405. #.................##
  406. ##...............###
  407. ##................##
  408. ##S##############G##
  409.  
  410. ####################
  411. #.................##
  412. #..................#
  413. #..................#
  414. ##################.#
  415. #...#..............#
  416. ###.#..............#
  417. ###................#
  418. ###...............##
  419. ##................##
  420. ##.#################
  421. ##..################
  422. ###.################
  423. ##..#..............#
  424. ##.#########.#######
  425. #.................##
  426. #.................##
  427. ##...............###
  428. ##++++++++++++++++##
  429. ##S##############G##
  430.  
  431.  
  432. Solving maze in maze4.txt
  433. ####################
  434. #.................##
  435. #..................#
  436. #..................#
  437. ##################.#
  438. #...#..............#
  439. ###.#..............#
  440. ###................#
  441. ###...............##
  442. ##................##
  443. ##.#################
  444. ##..################
  445. ###.################
  446. ##..#..............#
  447. ##.#########.#######
  448. #.................##
  449. #.................##
  450. ##...............###
  451. ##..............#.##
  452. ##S##############G##
  453.  
  454. this maze is unsolvable.
  455. ####################
  456. #.................##
  457. #..................#
  458. #..................#
  459. ##################.#
  460. #...#..............#
  461. ###.#..............#
  462. ###................#
  463. ###...............##
  464. ##................##
  465. ##.#################
  466. ##..################
  467. ###.################
  468. ##..#..............#
  469. ##.#########.#######
  470. #.................##
  471. #.................##
  472. ##...............###
  473. ##..............#.##
  474. ##S##############G##
  475. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement