Wednesday, March 2, 2022

N Queens

I/P: 4

O/P:
0-1, 1-3, 2-0, 3-2, . 0-2, 1-0, 2-3, 3-1, .











package pep.Day12;

public class N_Queens {
public static void main(String[] args) throws Exception {
int[][] chess = new int[4][4];
printNQueens(chess, "", 0);
}


public static void printNQueens(int[][] chess, String qsf, int row) {
if (row == chess.length) {
System.out.println(qsf + ".");
return;
}

for (int col = 0; col < chess.length; col++) {
if (isSafePlaceForTheQueen(chess, row, col)) {
chess[row][col] = 1;
printNQueens(chess, (qsf + row + "-" + col + ", "), row + 1);
chess[row][col] = 0;
}
}
}

private static boolean isSafePlaceForTheQueen(int[][] chess, int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < chess[0].length; j++) {
// right diagonal, left diagonal
if (((i + j == row + col) || (i - j == row - col)) && chess[i][j] == 1)
return false;

// upwards
if (chess[i][col] == 1)
return false;
}
}
return true;
}
}
private static boolean isSafePlaceForTheQueen(int[][] chess, int row, int col) {
// upwards
for (int i = row - 1, j = col; i >= 0; i--)
if (chess[i][j] == 1)
return false;

// left diagonal
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--)
if (chess[i][j] == 1)
return false;

// right diagonal
for (int i = row - 1, j = col + 1; i >= 0 && j < chess.length; i--, j++)
if (chess[i][j] == 1)
return false;

return true;
}



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:...