Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- public class KnightsTour1 {
- int[][] board = new int[8][8];
- int[] horizontal = {1, 2, 2, 1, -1, -2, -2, -1};
- int[] vertical = {-2, -1, 1, 2, 2, 1, -1, -2};
- int row = 0;
- int col = 0;
- int end = 0;
- public void start () {
- board[row][col] = 1;
- }
- public void play () {
- Random dhanya = new Random ();
- for (int i = 2; i <= 64; i++) {
- int random = dhanya.nextInt(8);
- if (row + horizontal[random] < 0 || row + horizontal[random] > 7 || col + vertical[random] < 0 || col + vertical[random] > 7 || board[row + horizontal[random]][col + vertical[random]] != 0) {
- for (int j = 1; j < 8; j++) {
- if (row + horizontal[j] < 0 || row + horizontal[j] > 7 || col + vertical[j] < 0 || col + vertical[j] > 7 || board[row + horizontal[j]][col + vertical[j]] != 0) {
- if (j == 8) {
- end = i;
- i = 64;
- }
- }
- else {
- row = row + horizontal[j];
- col = col + vertical[j];
- board[row][col] = i;
- end = i;
- break;
- }
- }
- }
- else {
- row = row + horizontal[random];
- col = col + vertical[random];
- board[row][col] = i;
- end = i;
- }
- }
- }
- public void printTable() {
- for (int i = 0; i <= 8; i++) {
- if (i == 0) {
- System.out.printf("%4s", " ");
- }
- else
- System.out.printf("%4d", i);
- }
- System.out.println();
- for (int row = 0; row < board.length; row++) {
- System.out.printf("%4d", row + 1);
- for (int col = 0; col < board[row].length; col++) {
- System.out.printf("%4d", board[row][col]);
- }
- System.out.println();
- }
- System.out.println("\t" + end + " Squares Were Visited.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement