Pages

Wednesday, August 13, 2025

N Queens - all ways in Java

 

1. Missing curly braces after class declaration

java
public class Classroom

should be:

java
public class Classroom {

2. Wrong way of representing '.' in char

You are using:

java
board[row][j] = ".";
  • This is a String, not a char.

  • Since your board is char[][], use single quotes:

java
board[row][j] = '.';

3. Strings[] args should be String[] args

java
public static void main(Strings[] args)

must be:

java
public static void main(String[] args)

4. board.length() is wrong

length() is for methods (like String).
For arrays, use .length without parentheses:

java
for(int i=0; i<board.length; i++) { for(int j=0; j<board.length; j++) {

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:

java



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

Multi-dimensional ArrayList in Java

  // import java.util.ArrayList; import java.util. * ; // import java.util.Collections; public class Classroom {     public static voi...