Monday, March 7, 2022

KnightsTour

I/P:

5

2

0


O/P:

25 2 13 8 23 

12 7 24 3 14 

1 18 15 22 9 

6 11 20 17 4 

19 16 5 10 21 


19 2 13 8 21 

12 7 20 3 14 

1 18 15 22 9 

6 11 24 17 4 

25 16 5 10 23 ...

img



package pep.Day12;

import java.util.Scanner;

public class KnightsTour {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

int n = sc.nextInt();
int r = sc.nextInt();
int c = sc.nextInt();

int[][] chess = new int[n][n];

printKnightsTour(chess, r, c, 1);
}

public static void printKnightsTour(int[][] chess, int r, int c, int upcomingMove) {
if (r < 0 || c < 0 || r >= chess.length || c >= chess.length || chess[r][c] != 0)
return;
else if (upcomingMove == chess.length * chess.length) {
// update chess.length * chess.length's move
chess[r][c] = upcomingMove;
displayBoard(chess);
// again update to 0 for the further process
chess[r][c] = 0;
return;
}


int[][] dirns = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1},
{2, -1}, {1, -2}, {-1, -2}, {-2, -1}};

chess[r][c] = upcomingMove;
for (int[] dir : dirns) {
printKnightsTour(chess, r + dir[0], c + dir[1], upcomingMove + 1);
}
// this is used in fallback when no block present to move further
chess[r][c] = 0;
}

public static void displayBoard(int[][] chess) {
for (int i = 0; i < chess.length; i++) {
for (int j = 0; j < chess[0].length; j++) {
System.out.print(chess[i][j] + " ");
}
System.out.println();
}

System.out.println();
}
}








No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...