Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class KnightsTour
- {
- int[][] board = new int[9][9];
- int[][] moving = {{1, 2, 2, 1, -1, -2, -2, - 1},
- {-2, -1, 1, 2, 2, 1, - 1, -2}};
- public KnightsTour()
- {
- board[1][1] = 1;
- }
- public void move()
- {
- int x = 1;
- int y = 1;
- board[x][y] = 1;
- int counter = 1;
- //perhaps a for loop instead of recursion
- //recursion is why i was getting a error for my random
- //sos room check: was not checking if the spot was already taken
- for(int u = 2; u <= 64; u++)
- {
- int xHolder = x;
- int yHolder = y;
- int moveToNum = (int)( Math.random() * 8);
- x += moving[0][moveToNum];
- y += moving[1][moveToNum];
- //board[x][y] = counter;
- while( notLegalMove(x, y) || !notTakenSpot(x, y) )
- {
- moveToNum = (int)(Math.random() * 8);
- x = xHolder + moving[0][moveToNum];
- y = yHolder + moving[1][moveToNum];
- counter++;
- if(counter >= 20)
- break;
- }
- if( notLegalMove(x, y) || !notTakenSpot(x, y))
- {
- break;
- }
- board[x][y] = u;
- counter = 1;
- //cordinates
- //ramdomly select move then check if it works, if not, repeat
- }
- }
- public boolean notTakenSpot(int x, int y)
- {
- if(board[x][y] == 0)
- return true;
- else
- return false;
- }
- public boolean notLegalMove(int x, int y)
- {
- //this is where i'm trying to fix
- if( x < 1 || x >= 9 || y < 1 || y >= 9 )
- return true;
- else
- return false;
- }
- public void printBoard(){
- System.out.print(" ");
- for(int h = 1; h < 9; h++)
- {
- System.out.print(h + " ");
- }
- System.out.println();
- for(int i = 1; i < 9; i++)
- {
- System.out.print(i + " ");
- for(int j = 1; j < 9; j++)
- {
- if(board[i][j] < 10)
- System.out.print(" " + board[i][j]);
- else
- System.out.print(" " + board[i][j]);
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement