0% found this document useful (0 votes)
23 views2 pages

Java Solution for N-Queens Problem

The document contains a Java implementation of the N-Queens problem, which involves placing N queens on an N x N chessboard such that no two queens threaten each other. It includes methods for checking if a position is safe for a queen, backtracking to find a solution, and printing the board configuration. The main method allows for solving the problem for a specified value of N, defaulting to 8.

Uploaded by

rachi.website
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views2 pages

Java Solution for N-Queens Problem

The document contains a Java implementation of the N-Queens problem, which involves placing N queens on an N x N chessboard such that no two queens threaten each other. It includes methods for checking if a position is safe for a queen, backtracking to find a solution, and printing the board configuration. The main method allows for solving the problem for a specified value of N, defaulting to 8.

Uploaded by

rachi.website
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

public class NQueens {

// Method to print the solution


static void printSolution(int board[][], int N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
[Link](board[i][j] == 1 ? "Q " : ". ");
}
[Link]();
}
}

// Method to check if a queen can be placed on board[row][col]


static boolean isSafe(int board[][], int row, int col, int N) {
// Check the column
for (int i = 0; i < row; i++) {
if (board[i][col] == 1) {
return false;
}
}

// Check upper-left diagonal


for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 1) {
return false;
}
}

// Check upper-right diagonal


for (int i = row, j = col; i >= 0 && j < N; i--, j++) {
if (board[i][j] == 1) {
return false;
}
}

return true;
}

// Backtracking method to solve the N-Queens problem


static boolean solveNQueensUtil(int board[][], int row, int N) {
// If all queens are placed
if (row == N) {
return true;
}

// Try placing the queen in all columns one by one


for (int col = 0; col < N; col++) {
if (isSafe(board, row, col, N)) {
board[row][col] = 1; // Place the queen

// Recur to place the rest of the queens


if (solveNQueensUtil(board, row + 1, N)) {
return true;
}

// If placing queen in board[row][col] doesn't lead to a solution,


backtrack
board[row][col] = 0;
}
}

return false; // If the queen cannot be placed in any column


}

// Method to solve the N-Queens problem


static boolean solveNQueens(int N) {
int board[][] = new int[N][N];

if (!solveNQueensUtil(board, 0, N)) {
[Link]("Solution does not exist");
return false;
}

printSolution(board, N);
return true;
}

public static void main(String[] args) {


int N = 8; // You can change this value to solve for different N
solveNQueens(N);
}
}

Common questions

Powered by AI

The time complexity of the NQueens algorithm is O(N!), as the algorithm tries to place a queen in each row and checks for its safety in each column and potentially across diagonals. The `isSafe` method alone has a complexity of O(N) because it checks each of the three directions (column and two diagonals) per queen placement. As N grows, the computational complexity increases factorially, making it less efficient for large N values .

Backtracking in the NQueens problem is used to explore possible positions for queens one row at a time. If placing a queen leads to a solution, the algorithm returns `true`. If not, it removes the queen (backtracks) and tries the next column. This process is repeated until all queens are placed safely or all possibilities are exhausted, at which point the puzzle is deemed unsolvable for that configuration .

When the `solveNQueens` method is executed with an input value of 8, the method attempts to solve the 8-queens problem. It initializes an 8x8 board and uses the `solveNQueensUtil` method to try placing queens row by row. If a solution is found, it prints the board configuration. If no solution is possible, it outputs 'Solution does not exist'. For N=8, a solution does exist, and the method will print one of the multiple possible configurations .

The `printSolution` method is essential in the NQueens algorithm as it outputs the board representing a successful placement of queens. It uses a nested loop to check each cell, printing 'Q' if a queen is present or '.' if the space is empty. This visual representation helps in understanding and verifying the correct placement of all queens on the board .

The NQueens algorithm ensures that queens are placed safely on the board by using the `isSafe` method. This method checks three conditions for safety: 1) it verifies that there are no other queens in the same column above the current row; 2) it checks the upper-left diagonal for any queens; 3) it checks the upper-right diagonal. If these conditions are met, it is safe to place a queen at the specified position .

The `isSafe` function evaluates the viability of placing a queen in a given position by checking three potential lines of attack: it ensures no queens are in the same column by iterating from the top of the current column to the current row; it checks the upper-left diagonal by decrementing both row and column indices simultaneously; finally, it checks the upper-right diagonal by decrementing the row index and incrementing the column index. If none of these lines contain a queen, the position is deemed safe .

The `solveNQueensUtil` method returns `true` when all queens have been placed successfully on the board, which corresponds to the base case where `row == N`. This implies that all rows have been processed and a valid configuration has been found. The method returns `false` in all other cases after trying all possibilities in a given configuration .

The loop in `solveNQueensUtil` starts from column 0 during each row iteration to ensure that the algorithm systematically explores all possible column positions within a row before concluding no safe position exists. This exhaustive search is crucial for implementing backtracking, as it allows the algorithm to fully explore and retreat as needed when searching for a valid configuration .

To modify the `solveNQueens` algorithm to find all possible solutions, you would adjust the `solveNQueensUtil` method to not immediately return true upon finding a solution. Instead, it would continue to explore other column placements by not returning after a successful recursive call and backtracking further to explore additional possibilities. This could involve adding a list to store solutions and a mechanism to accumulate them through recursion .

The scalability of the NQueens problem is inherently limited by its factorial time complexity. As N increases, the number of possible configurations that need evaluation grows rapidly, making the problem computationally expensive. For large values, resource consumption in terms of both time and memory becomes impractically high due to the exponential growth in permutations. Advancements in algorithm optimization or parallel processing are necessary to efficiently handle higher values of N within reasonable computational limits .

You might also like