Advertisement
gluten_free_feeling

YETANOTHERKNIGHTSTOUR

Feb 10th, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. public class KnightsTour
  2. {
  3. int[][] board = new int[9][9];
  4. int[][] moving = {{1, 2, 2, 1, -1, -2, -2, - 1},
  5. {-2, -1, 1, 2, 2, 1, - 1, -2}};
  6.  
  7. public KnightsTour()
  8. {
  9. board[1][1] = 1;
  10. }
  11.  
  12. public void move()
  13. {
  14. int x = 1;
  15. int y = 1;
  16. board[x][y] = 1;
  17. int counter = 1;
  18. //perhaps a for loop instead of recursion
  19. //recursion is why i was getting a error for my random
  20. //sos room check: was not checking if the spot was already taken
  21. for(int u = 2; u <= 64; u++)
  22. {
  23. int xHolder = x;
  24. int yHolder = y;
  25.  
  26. int moveToNum = (int)( Math.random() * 8);
  27. x += moving[0][moveToNum];
  28. y += moving[1][moveToNum];
  29.  
  30. //board[x][y] = counter;
  31.  
  32. while( notLegalMove(x, y) || !notTakenSpot(x, y) )
  33. {
  34. moveToNum = (int)(Math.random() * 8);
  35. x = xHolder + moving[0][moveToNum];
  36. y = yHolder + moving[1][moveToNum];
  37. counter++;
  38. if(counter >= 20)
  39. break;
  40. }
  41. if( notLegalMove(x, y) || !notTakenSpot(x, y))
  42. {
  43. break;
  44. }
  45. board[x][y] = u;
  46. counter = 1;
  47. //cordinates
  48. //ramdomly select move then check if it works, if not, repeat
  49. }
  50. }
  51.  
  52. public boolean notTakenSpot(int x, int y)
  53. {
  54. if(board[x][y] == 0)
  55. return true;
  56. else
  57. return false;
  58. }
  59.  
  60. public boolean notLegalMove(int x, int y)
  61. {
  62. //this is where i'm trying to fix
  63. if( x < 1 || x >= 9 || y < 1 || y >= 9 )
  64. return true;
  65. else
  66. return false;
  67. }
  68.  
  69. public void printBoard(){
  70. System.out.print(" ");
  71. for(int h = 1; h < 9; h++)
  72. {
  73. System.out.print(h + " ");
  74. }
  75. System.out.println();
  76. for(int i = 1; i < 9; i++)
  77. {
  78. System.out.print(i + " ");
  79. for(int j = 1; j < 9; j++)
  80. {
  81. if(board[i][j] < 10)
  82. System.out.print(" " + board[i][j]);
  83. else
  84. System.out.print(" " + board[i][j]);
  85. }
  86. System.out.println();
  87. }
  88. }
  89.  
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement