1. Missing curly braces after class declaration
should be:
2. Wrong way of representing '.'
in char
You are using:
-
This is a String, not a
char
. -
Since your board is
char[][]
, use single quotes:
3. Strings[] args
should be String[] args
must be:
4. board.length()
is wrong
length()
is for methods (like String).
For arrays, use .length
without parentheses:
5. Your main
method is misplaced
You placed main
inside { }
outside any method, which is invalid.
It should be inside the Classroom
class, not after random { }
.
6. Initialization of board
Same issue as point 2 — you need to use '.'
instead of "."
.
✅ Here’s the corrected code:
import java.util.*;
public class Classroom {
// function to place queens
public static void nQueens(char board[][], int row) {
// base case
if (row == board.length) {
printBoard(board);
return;
}
// column loop
for (int j = 0; j < board.length; j++) {
board[row][j] = 'Q'; // queen placed here
nQueens(board, row + 1); // recursive call
board[row][j] = '.'; // backtracking step
}
}
// print board
public static void printBoard(char board[][]) {
System.out.println("--------- chess board ---------");
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int n = 2;
char board[][] = new char[n][n];
// initialize board with '.'
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
board[i][j] = '.';
}
}
nQueens(board, 0);
}
}
OUTPUT:
--------- chess board ---------
Q .
Q .
--------- chess board ---------
Q .
. Q
--------- chess board ---------
. Q
Q .
--------- chess board ---------
. Q
. Q
No comments:
Post a Comment