Skip to content

Commit 6f51084

Browse files
committed
knight problem code added
1 parent 52c416e commit 6f51084

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

Backtracking/Knight's_Tour.java

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*Moving according to the rules of chess knight must visit each square exactly once. Print the order of each the cell in which they are visited.*/
2+
import java.util.*;
3+
public class MyClass {
4+
public static void main(String args[]) {
5+
Scanner sc = new Scanner(System.in);
6+
int n = sc.nextInt();
7+
// provide start position
8+
int r = sc.nextInt();
9+
int c = sc.nextInt();
10+
int board[][] = new int[n][n];
11+
// The 8 possible moves where a knight can move from its current position
12+
int posx[] = {-1,-1,1,1,-2,-2,2,2};
13+
int posy[] = {-2,2,-2,2,-1,1,-1,1};
14+
path(board, r, c, 1, posx, posy);
15+
}
16+
public static boolean path(int board[][], int row, int col, int move, int posx[], int posy[]) {
17+
board[row][col] = move;
18+
// if all the positions are visited then print the result
19+
if (move == board.length*board.length) {
20+
// printing result in matrix form
21+
for (int i = 0; i < board.length; i++) {
22+
for (int j = 0; j < board.length; j++)
23+
if (board[i][j] < 10)
24+
System.out.print("0" + board[i][j] + " ");
25+
else
26+
System.out.print(board[i][j] + " ");
27+
System.out.println();
28+
}
29+
return true;
30+
}
31+
for (int i = 0; i < 8; i++) {
32+
int newx = row + posx[i];
33+
int newy = col + posy[i];
34+
// checking if the new position is a valid move and not visited yet
35+
if (validmove(newx, newy, board) && board[newx][newy] == 0) {
36+
if (path(board, newx, newy, move + 1, posx, posy)) {
37+
return true;
38+
}
39+
}
40+
}
41+
// if position is not valid mark position as unvisited in the matrix
42+
board[row][col] = 0;
43+
return false;
44+
}
45+
// checks that the new position is not outside the matrix of n*n
46+
static boolean validmove(int newx, int newy, int board[][]) {
47+
if (newx >= 0 && newx < board.length && newy >= 0 && newy < board.length)
48+
return true;
49+
return false;
50+
}
51+
}
52+
53+
/*Input
54+
8
55+
0
56+
0
57+
Output
58+
01 08 15 22 03 10 19 64
59+
16 23 02 09 18 21 04 11
60+
07 14 17 24 05 12 63 20
61+
34 25 06 13 44 27 52 61
62+
55 46 33 26 53 62 43 28
63+
32 35 54 45 40 29 60 51
64+
47 56 37 30 49 58 39 42
65+
36 31 48 57 38 41 50 59 */

0 commit comments

Comments
 (0)