Advertisement
Guest User

Knight Tour

a guest
Mar 2nd, 2015
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. package horsejump;
  2.  
  3. import java.util.LinkedList;
  4. import java.util.List;
  5.  
  6.  
  7. public class Knight_Tour {
  8.  
  9. Board board;
  10. Pos currentPos;
  11. private boolean complete = false;
  12. private final Pos[] JUMP = { new Pos(2,1), new Pos(2,-1),
  13. new Pos(-2,1), new Pos(-2,-1), new Pos(1,2),
  14. new Pos(1,-2), new Pos(-1,2), new Pos(-1,-2)};
  15. int[] bestchoice;
  16. Pos followUp;
  17.  
  18. public Knight_Tour(int boardsize){
  19. this(boardsize, new Pos(0,0));
  20. }
  21.  
  22.  
  23. public Knight_Tour(int boardsize, Pos start){
  24. board = new Board(boardsize);
  25. bestchoice = new int[JUMP.length];
  26. solve(start, 0);
  27. }
  28.  
  29. public Pos[] getOptions(Pos current, int boardsize){
  30.  
  31. List<Pos> result = new LinkedList<Pos>();
  32.  
  33. for(Pos option: JUMP){
  34. int x = current.getX() + option.getX();
  35. int y = current.getY() + option.getY();
  36. Pos futurePos = new Pos(x,y);
  37. if(x >= 0 && x < boardsize && y >= 0 && y < boardsize){
  38. if(board.getBoard(futurePos) == 0){
  39. result.add (futurePos);
  40. }
  41. }
  42. }
  43. //System.out.println(options);
  44. return result.toArray(new Pos[result.size()]);
  45. }
  46.  
  47. public boolean solve(Pos current, int steps){
  48. System.out.println(board);
  49. if (boardFilled()) {
  50. System.out.println(board);
  51. return true;
  52. }
  53.  
  54. Pos [] successors = getOptions (current,board.getBoardsize());
  55.  
  56. if (successors.length == 0) {
  57.  
  58. return false;
  59. }
  60.  
  61. for (int i = 0; i < successors.length; i++) {
  62. followUp = successors [i];
  63. board.set(followUp, steps);
  64. if (solve (followUp, steps+1)) {
  65. return true;
  66. } else {
  67. board.set(followUp, 0);
  68. }
  69.  
  70. }
  71. return false;
  72. }
  73.  
  74.  
  75. public boolean boardFilled(){
  76. for (int i = 0; i < board.getBoardsize(); i++) {
  77. for (int j = 0; j < board.getBoardsize(); j++) {
  78. Pos pos = new Pos (i,j);
  79. if (board.getBoard(pos) == 0) {
  80. return false;
  81. }
  82. }
  83. }
  84. return true;
  85. }
  86.  
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement