Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public String backtrack(int row, int col, String pathSoFar)
- {
- // TODO: write the recursive backtrack algorithm.
- // fix the return value!
- String out = null;
- int steps = 0;
- markers[row][col] = true;
- if (row == 0 && col == 0
- || row == 0 && col == SIDE_LENGTH
- || row == SIDE_LENGTH && col == 0
- || row == SIDE_LENGTH && col == SIDE_LENGTH)
- {
- return "Found Solution:" + pathSoFar;
- }
- else
- {
- steps = map[row][col];
- if (validateMove(row + steps, col)
- && validateMove(row - steps, col)
- && validateMove(row, col - steps)
- && validateMove(row, col + steps))
- {
- out = move(steps, row, col, pathSoFar);
- }
- }
- return out;
- }
- /**
- * Move.
- * Runs the moves as
- * @param steps int
- * @param row int
- * @param col int
- * @param pathSoFar string
- * @return String
- */
- public String move(int steps, int row, int col, String pathSoFar)
- {
- String out = "";
- if (markers[row - steps][col] != true)
- {
- out = backtrack(row - steps, col, pathSoFar + "up");
- if (out != null)
- {
- return out;
- }
- }
- else if (markers[row + steps][col] != true)
- {
- out = backtrack(row + steps, col, pathSoFar + "down");
- if (out != null)
- {
- return out;
- }
- }
- else if (markers[row][col - steps] != true)
- {
- out = backtrack(row, col + steps, pathSoFar + "right");
- if (out != null)
- {
- return out;
- }
- }
- else if (markers[row][col + steps] != true)
- {
- out = backtrack(row, col - steps, pathSoFar + "left");
- if (out != null)
- {
- return out;
- }
- }
- return out;
- }
- /**
- * Validate move.
- * Makes sure the move is valid.
- * @param row int.
- * @param col int
- * @return Boolean.
- */
- public Boolean validateMove(int row, int col)
- {
- boolean out = true;
- if (row < SIDE_LENGTH && col < SIDE_LENGTH)
- {
- out = false;
- }
- return out;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement