Advertisement
Guest User

Untitled

a guest
Nov 25th, 2014
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. public String backtrack(int row, int col, String pathSoFar)
  2. {
  3. // TODO: write the recursive backtrack algorithm.
  4. // fix the return value!
  5. String out = null;
  6. int steps = 0;
  7. markers[row][col] = true;
  8.  
  9. if (row == 0 && col == 0
  10. || row == 0 && col == SIDE_LENGTH
  11. || row == SIDE_LENGTH && col == 0
  12. || row == SIDE_LENGTH && col == SIDE_LENGTH)
  13. {
  14. return "Found Solution:" + pathSoFar;
  15. }
  16. else
  17. {
  18. steps = map[row][col];
  19. if (validateMove(row + steps, col)
  20. && validateMove(row - steps, col)
  21. && validateMove(row, col - steps)
  22. && validateMove(row, col + steps))
  23. {
  24. out = move(steps, row, col, pathSoFar);
  25. }
  26. }
  27.  
  28. return out;
  29. }
  30.  
  31. /**
  32. * Move.
  33. * Runs the moves as
  34. * @param steps int
  35. * @param row int
  36. * @param col int
  37. * @param pathSoFar string
  38. * @return String
  39. */
  40. public String move(int steps, int row, int col, String pathSoFar)
  41. {
  42. String out = "";
  43.  
  44. if (markers[row - steps][col] != true)
  45. {
  46. out = backtrack(row - steps, col, pathSoFar + "up");
  47. if (out != null)
  48. {
  49. return out;
  50. }
  51. }
  52. else if (markers[row + steps][col] != true)
  53. {
  54. out = backtrack(row + steps, col, pathSoFar + "down");
  55. if (out != null)
  56. {
  57. return out;
  58. }
  59. }
  60. else if (markers[row][col - steps] != true)
  61. {
  62. out = backtrack(row, col + steps, pathSoFar + "right");
  63. if (out != null)
  64. {
  65. return out;
  66. }
  67. }
  68. else if (markers[row][col + steps] != true)
  69. {
  70. out = backtrack(row, col - steps, pathSoFar + "left");
  71. if (out != null)
  72. {
  73. return out;
  74. }
  75. }
  76. return out;
  77. }
  78.  
  79. /**
  80. * Validate move.
  81. * Makes sure the move is valid.
  82. * @param row int.
  83. * @param col int
  84. * @return Boolean.
  85. */
  86. public Boolean validateMove(int row, int col)
  87. {
  88. boolean out = true;
  89. if (row < SIDE_LENGTH && col < SIDE_LENGTH)
  90. {
  91. out = false;
  92. }
  93.  
  94. return out;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement