Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class KnightTour {
- private int board[][];
- private int notvisted = 0;
- private int count = 1;
- private int x1;// start position
- private int y1;// start position
- private static int boardX;
- private static int boardY;
- public KnightTour(int boardX, int boardY, int x1, int y1) {
- this.x1 = x1;
- this.y1 = y1;
- this.boardX = boardX;
- this.boardY = boardY;
- board = new int[boardX][boardY];
- reset(board, boardX, boardY);
- }
- public void tour(int x, int y) {
- if ((y - 2 > 0 && x + 1 < boardX) && (board[x][y] == notvisted)) {
- board[x][y] = count;
- count++;
- }
- if ((y - 2 > 0 && x - 1 > 0) && (board[x][y] == notvisted)) {
- board[x][y] = count;
- count++;
- }
- if ((y - 1 > 0 && x - 2 > 0) && (board[x][y] == notvisted)) {
- board[x][y] = count;
- count++;
- }
- if ((y + 1 < boardY && x - 2 > 0) && (board[x][y] == notvisted)) {
- board[x][y] = count;
- count++;
- }
- if ((y + 2 < boardY && x - 1 > 0) && (board[x][y] == notvisted)) {
- board[x][y] = count;
- count++;
- }
- if ((y + 2 < boardY && x + 1 < boardX) && (board[x][y] == notvisted)) {
- board[x][y] = count;
- count++;
- }
- if ((y - 1 > 0 && x - 2 > 0) && (board[x][y] == notvisted)) {
- board[x][y] = count;
- count++;
- }
- if ((y + 1 < boardY && x - 2 > 0) && (board[x][y] == notvisted)) {
- board[x][y] = count;
- count++;
- }
- }
- public boolean reset(int board[][], int boardX, int boardY) {// setting all
- // the
- // fields
- // with
- // zeros
- for (int i = 0; i < boardY; i++) {
- for (int j = 0; j < boardX; j++) {
- board[i][j] = 0;
- }
- }
- return true;
- }
- public void print() {
- for (int row = 0; row < boardX; row++) {
- for (int col = 0; col < boardY; col++) {
- System.out.print("|");
- System.out.print("" + board[row][col]);
- }
- System.out.println("|");
- }
- }
- public static void main(String[] args) {
- KnightTour KnightTour = new KnightTour(8, 8, 0, 0);
- KnightTour.print();
- System.out.println();
- KnightTour.tour(0, 0);
- KnightTour.print();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement