Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.98 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class MazeSolver {
  5. static class P implements Comparable<P> {
  6. public int r, c;
  7. public int dist;
  8. public P prev;
  9. public P(int row, int col) {
  10. r = row;
  11. c = col;
  12. dist = 0;
  13. prev = null;
  14. }
  15. public P extend(int row, int col, int dist) {
  16. P ret = new P(row, col);
  17. ret.dist = this.dist + dist;
  18. ret.prev = this;
  19. return ret;
  20. }
  21. public int compareTo(P other) {
  22. // if this < other, return negative
  23. // if this == other, return 0
  24. // if this > other, return positive
  25. return Integer.compare(this.dist, other.dist);
  26. }
  27. public boolean equals(Object other1) {
  28. P other = (P) other1;
  29. return this.row == other.row && this.col == other.col;
  30. }
  31. public int hashCode() {
  32. return this.row * 137 + this.col;
  33. }
  34. }
  35. public static void main(String[] argv) throws IOException {
  36. Scanner sc = new Scanner(new File("data.dat"));
  37. int rows = sc.nextInt(), cols = sc.nextInt(); sc.nextLine();
  38. char[][] grid = new char[rows][];
  39. P start = null, end = null;
  40. for (int i = 0; i < rows; i++) {
  41. grid[i] = sc.nextLine().toCharArray();
  42. for (int j = 0; j < cols; j++) {
  43. if (grid[i][j] == '@') {
  44. start = new P(i, j);
  45. }
  46. if (grid[i][j] == '$') {
  47. end = new P(i, j);
  48. }
  49. }
  50. }
  51. HashSet<P> visited = new HashSet<>();
  52. PriorityQueue<P> Q = new PriorityQueue<>();
  53. Q.add(start);
  54. while (!Q.isEmpty()) {
  55. P cur = Q.remove();
  56. if (visited.contains(cur)) continue;
  57. visited.add(cur);
  58. if (cur.equals(end)) {
  59. end = cur;
  60. break;
  61. }
  62. for (int dr = -1; dr <= 1; dr++) {
  63. for (int dc = -1; dc <= 1; dc++) {
  64. // both r and c in [-1, 1]
  65. if (Math.abs(dr) == Math.abs(dc)) {
  66. continue;
  67. }
  68. int nr = cur.r + dr, nc = cur.c + dc;
  69. if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
  70. int dist = 1;
  71. if (grid[nr][nc] == '#') continue;
  72. if (grid[nr][nc] == '^') dist = 5;
  73. Q.add(cur.extend(cur.r + dr, cur.c + dc), dist);
  74. }
  75. }
  76. }
  77. // end contains the whole chain and total distance
  78. // example: if you want in order
  79. ArrayList<P> path = new ArrayList<P>();
  80. P cur = end;
  81. while (cur != null) {
  82. path.add(cur); // added backwards
  83. cur = cur.prev;
  84. }
  85. Collections.reverse(path);
  86. // if you don't care, instead of adding to arraylist, work with it
  87. }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement