We have discussed Knight’s tour and Rat in a Maze problem earlier as examples of Backtracking problems. Let us discuss N Queen as another example problem that can be solved using backtracking.
N-Queen Problem:
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, the following is a solution for the 4 Queen problem.

Solution for 4-Queen problem
The expected output is in the form of a matrix that has ‘Q‘s for the blocks where queens are placed and the empty spaces are represented by ‘.’ . For example, the following is the output matrix for the above 4-Queen solution.
. . Q .
Q . . .
. . . Q
. Q . .
Naive Algorithm:
Generate all possible configurations of queens on board and print a configuration that satisfies the given constraints.
while there are untried configurations
{
generate the next configuration
if queens don’t attack in this configuration then
{
print this configuration;
}
}
Time Complexity: O(N*NCN)
Auxiliary Space: O(N2)
Algorithm for N queen problem:
Following is the backtracking algorithm for solving the N-Queen problem
- Initialize an empty chessboard of size NxN.
- Start with the leftmost column and place a queen in the first row of that column.
- Move to the next column and place a queen in the first row of that column.
- Repeat step 3 until either all N queens have been placed or it is impossible to place a queen in the current column without violating the rules of the problem.
- If all N queens have been placed, print the solution.
- If it is not possible to place a queen in the current column without violating the rules of the problem, backtrack to the previous column.
- Remove the queen from the previous column and move it down one row.
- Repeat steps 4-7 until all possible configurations have been tried.
Pseudo-code implementation:
function solveNQueens(board, col, n):
if col >= n:
print board
return true
for row from 0 to n-1:
if isSafe(board, row, col, n):
board[row][col] = 1
if solveNQueens(board, col+1, n):
return true
board[row][col] = 0
return false
function isSafe(board, row, col, n):
for i from 0 to col-1:
if board[row][i] == 1:
return false
for i,j from row-1, col-1 to 0, 0 by -1:
if board[i][j] == 1:
return false
for i,j from row+1, col-1 to n-1, 0 by 1, -1:
if board[i][j] == 1:
return false
return true
board = empty NxN chessboard
solveNQueens(board, 0, N)
Backtracking Algorithm by placing queens in columns:
The idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes, then we backtrack and return false.
Follow the steps mentioned below to implement the idea:
- Start in the leftmost column
- If all queens are placed return true
- Try all rows in the current column. Do the following for every tried row.
- If the queen can be placed safely in this row
- Then mark this [row, column] as part of the solution and recursively check if placing queen here leads to a solution.
- If placing the queen in [row, column] leads to a solution then return true.
- If placing queen doesn’t lead to a solution then unmark this [row, column] and track back and try other rows.
- If all rows have been tried and nothing worked return false to trigger backtracking.
Implementation of the above backtracking solution:
C
#define N 4
#include <stdbool.h>
#include <stdio.h>
void printSolution( int board[N][N])
{
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < N; j++) {
if (board[i][j])
printf ( "Q " );
else
printf ( ". " );
}
printf ( "\n" );
}
}
bool isSafe( int board[N][N], int row, int col)
{
int i, j;
for (i = 0; i < col; i++)
if (board[row][i])
return false ;
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false ;
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false ;
return true ;
}
bool solveNQUtil( int board[N][N], int col)
{
if (col >= N)
return true ;
for ( int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1;
if (solveNQUtil(board, col + 1))
return true ;
board[i][col] = 0;
}
}
return false ;
}
bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == false ) {
printf ( "Solution does not exist" );
return false ;
}
printSolution(board);
return true ;
}
int main()
{
solveNQ();
return 0;
}
|
C++
#include <bits/stdc++.h>
#define N 4
using namespace std;
void printSolution( int board[N][N])
{
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < N; j++)
if (board[i][j])
cout << "Q " ;
else cout<< ". " ;
printf ( "\n" );
}
}
bool isSafe( int board[N][N], int row, int col)
{
int i, j;
for (i = 0; i < col; i++)
if (board[row][i])
return false ;
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false ;
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false ;
return true ;
}
bool solveNQUtil( int board[N][N], int col)
{
if (col >= N)
return true ;
for ( int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1;
if (solveNQUtil(board, col + 1))
return true ;
board[i][col] = 0;
}
}
return false ;
}
bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == false ) {
cout << "Solution does not exist" ;
return false ;
}
printSolution(board);
return true ;
}
int main()
{
solveNQ();
return 0;
}
|
Java
public class NQueenProblem {
final int N = 4 ;
void printSolution( int board[][])
{
for ( int i = 0 ; i < N; i++) {
for ( int j = 0 ; j < N; j++) {
if (board[i][j] == 1 )
System.out.print( "Q " );
else
System.out.print( ". " );
}
System.out.println();
}
}
boolean isSafe( int board[][], int row, int col)
{
int i, j;
for (i = 0 ; i < col; i++)
if (board[row][i] == 1 )
return false ;
for (i = row, j = col; i >= 0 && j >= 0 ; i--, j--)
if (board[i][j] == 1 )
return false ;
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j] == 1 )
return false ;
return true ;
}
boolean solveNQUtil( int board[][], int col)
{
if (col >= N)
return true ;
for ( int i = 0 ; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1 ;
if (solveNQUtil(board, col + 1 ) == true )
return true ;
board[i][col] = 0 ;
}
}
return false ;
}
boolean solveNQ()
{
int board[][] = { { 0 , 0 , 0 , 0 },
{ 0 , 0 , 0 , 0 },
{ 0 , 0 , 0 , 0 },
{ 0 , 0 , 0 , 0 } };
if (solveNQUtil(board, 0 ) == false ) {
System.out.print( "Solution does not exist" );
return false ;
}
printSolution(board);
return true ;
}
public static void main(String args[])
{
NQueenProblem Queen = new NQueenProblem();
Queen.solveNQ();
}
}
|
Python3
global N
N = 4
def printSolution(board):
for i in range (N):
for j in range (N):
if board[i][j] = = 1 :
print ( "Q" ,end = " " )
else :
print ( "." ,end = " " )
print ()
def isSafe(board, row, col):
for i in range (col):
if board[row][i] = = 1 :
return False
for i, j in zip ( range (row, - 1 , - 1 ),
range (col, - 1 , - 1 )):
if board[i][j] = = 1 :
return False
for i, j in zip ( range (row, N, 1 ),
range (col, - 1 , - 1 )):
if board[i][j] = = 1 :
return False
return True
def solveNQUtil(board, col):
if col > = N:
return True
for i in range (N):
if isSafe(board, i, col):
board[i][col] = 1
if solveNQUtil(board, col + 1 ) = = True :
return True
board[i][col] = 0
return False
def solveNQ():
board = [[ 0 , 0 , 0 , 0 ],
[ 0 , 0 , 0 , 0 ],
[ 0 , 0 , 0 , 0 ],
[ 0 , 0 , 0 , 0 ]]
if solveNQUtil(board, 0 ) = = False :
print ( "Solution does not exist" )
return False
printSolution(board)
return True
if __name__ = = '__main__' :
solveNQ()
|
C#
using System;
class GFG
{
readonly int N = 4;
void printSolution( int [,]board)
{
for ( int i = 0; i < N; i++)
{
for ( int j = 0; j < N; j++)
{
if (board[i, j] == 1)
Console.Write( "Q " );
else
Console.Write( ". " );
}
Console.WriteLine();
}
}
bool isSafe( int [,]board, int row, int col)
{
int i, j;
for (i = 0; i < col; i++)
if (board[row,i] == 1)
return false ;
for (i = row, j = col; i >= 0 &&
j >= 0; i--, j--)
if (board[i,j] == 1)
return false ;
for (i = row, j = col; j >= 0 &&
i < N; i++, j--)
if (board[i, j] == 1)
return false ;
return true ;
}
bool solveNQUtil( int [,]board, int col)
{
if (col >= N)
return true ;
for ( int i = 0; i < N; i++)
{
if (isSafe(board, i, col))
{
board[i, col] = 1;
if (solveNQUtil(board, col + 1) == true )
return true ;
board[i, col] = 0;
}
}
return false ;
}
bool solveNQ()
{
int [,]board = {{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 }};
if (solveNQUtil(board, 0) == false )
{
Console.Write( "Solution does not exist" );
return false ;
}
printSolution(board);
return true ;
}
public static void Main(String []args)
{
GFG Queen = new GFG();
Queen.solveNQ();
}
}
|
Javascript
<script>
const N = 4
function printSolution(board)
{
for (let i = 0; i < N; i++)
{
for (let j = 0; j < N; j++)
{
if (board[i][j] == 1)
document.write( "Q " )
else
document.write( ". " )
}
document.write( "</br>" )
}
}
function isSafe(board, row, col)
{
for (let i = 0; i < col; i++){
if (board[row][i] == 1)
return false
}
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false
return true
}
function solveNQUtil(board, col){
if (col >= N)
return true
for (let i=0;i<N;i++){
if (isSafe(board, i, col)== true ){
board[i][col] = 1
if (solveNQUtil(board, col + 1) == true )
return true
board[i][col] = 0
}
}
return false
}
function solveNQ(){
let board = [ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0] ]
if (solveNQUtil(board, 0) == false ){
document.write( "Solution does not exist" )
return false
}
printSolution(board)
return true
}
solveNQ()
</script>
|
Output. . Q .
Q . . .
. . . Q
. Q . .
Time Complexity: O(N!)
Auxiliary Space: O(N2)
Backtracking Algorithm by placing queens in rows:
The idea is to place queens one by one in different rows, starting from the topmost row. When we place a queen in a row, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes, then we backtrack and return false.
Follow the steps mentioned below to implement the idea:
- Make a recursive function that takes the state of the board and the current row number as its parameter.
- Start in the topmost row.
- If all queens are placed return true
- Try all columns in the current row. Do the following for every tried column.
- If the queen can be placed safely in this column
- Then mark this [row, column] as part of the solution and recursively check if placing queen here leads to a solution.
- If placing the queen in [row, column] leads to a solution then return true.
- If placing queen doesn’t lead to a solution then unmark this [row, column] and track back and try other columns.
- If all columns have been tried and nothing worked return false to trigger backtracking.
Below is the implementation of the above Backtracking solution:
C++
#include <bits/stdc++.h>
using namespace std;
vector<vector<string> > answer;
void print_board()
{
for ( auto & str : answer[1]) {
for ( auto & letter : str)
cout << letter << " " ;
cout << endl;
}
return ;
}
int safe( int row, int col, vector<string>& board)
{
for ( int i = 0; i < board.size(); i++) {
if (board[i][col] == 'Q' )
return false ;
}
int i = row, j = col;
while (i >= 0 && j >= 0)
if (board[i--][j--] == 'Q' )
return false ;
i = row, j = col;
while (i >= 0 && j < board.size())
if (board[i--][j++] == 'Q' )
return false ;
return true ;
}
void rec(vector<string> board, int row)
{
if (row == board.size()) {
answer.push_back(board);
return ;
}
for ( int i = 0; i < board.size(); i++) {
if (safe(row, i, board)) {
board[row][i] = 'Q' ;
rec(board, row + 1);
board[row][i] = '.' ;
}
}
return ;
}
vector<vector<string> > solveNQueens( int n)
{
string s;
for ( int i = 0; i < n; i++)
s += '.' ;
vector<string> board(n, s);
rec(board, 0);
return answer;
}
int main()
{
clock_t start, end;
start = clock ();
cout << solveNQueens(4).size() << endl;
cout << "Out of " << answer.size()
<< " solutions one is following" << endl;
print_board();
return 0;
}
|
Java
import java.util.*;
public class NQueens {
static List<List<String> > answer = new ArrayList<>();
static void print_board()
{
for (String str : answer.get( 1 )) {
for (Character letter : str.toCharArray())
System.out.print(letter + " " );
System.out.println();
}
return ;
}
static boolean safe( int row, int col,
List<String> board)
{
for ( int i = 0 ; i < board.size(); i++) {
if (board.get(i).charAt(col) == 'Q' )
return false ;
}
int i = row, j = col;
while (i >= 0 && j >= 0 )
if (board.get(i--).charAt(j--) == 'Q' )
return false ;
i = row;
j = col;
while (i >= 0 && j < board.size())
if (board.get(i--).charAt(j++) == 'Q' )
return false ;
return true ;
}
static void rec(List<String> board, int row)
{
if (row == board.size()) {
answer.add(board);
return ;
}
for ( int i = 0 ; i < board.size(); i++) {
if (safe(row, i, board)) {
List<String> temp = new ArrayList<>(board);
temp.set(
row,
temp.get(row).substring( 0 , i) + "Q"
+ temp.get(row).substring(i + 1 ));
rec(temp, row + 1 );
}
}
return ;
}
static List<List<String> > solveNQueens( int n)
{
String s
= new String( new char [n]).replace( "\0" , "." );
List<String> board = new ArrayList<>();
for ( int i = 0 ; i < n; i++)
board.add(s);
rec(board, 0 );
return answer;
}
public static void main(String[] args)
{
System.out.println(solveNQueens( 4 ).size());
System.out.println( "Out of " + answer.size()
+ " solutions one is following" );
print_board();
}
}
|
Python3
import time
def print_board(board, n):
for i in range (n):
for j in range (n):
print (board[i][j], end = " " )
print ()
def add_sol(board, ans, n):
temp = []
for i in range (n):
string = ""
for j in range (n):
string + = board[i][j]
temp.append(string)
ans.append(temp)
def is_safe(row, col, board, n):
x = row
y = col
while (x> = 0 ):
if board[x][y] = = "Q" :
return False
else :
x - = 1
x = row
y = col
while (y<n and x> = 0 ):
if board[x][y] = = "Q" :
return False
else :
y + = 1
x - = 1
x = row
y = col
while (y> = 0 and x> = 0 ):
if board[x][y] = = "Q" :
return False
else :
x - = 1
y - = 1
return True
def solveNQueens(row, ans, board, n):
if row = = n:
add_sol(board, ans, n)
return
for col in range (n):
if is_safe(row, col, board, n):
board[row][col] = "Q"
solveNQueens(row + 1 , ans, board, n)
board[row][col] = "."
if __name__ = = "__main__" :
n = 4
board = [[ "." for i in range (n)] for j in range (n)]
ans = []
solveNQueens( 0 , ans, board, n)
if ans = = []:
print ( "Solution does not exist" )
else :
print ( len (ans))
print (f "Out Of {len(ans)} solutions one is following" )
print_board(ans[ 0 ], n)
|
C#
using System;
using System.Collections.Generic;
namespace NQueensProblem {
class Program {
static List<List< string > > answer
= new List<List< string > >();
static void PrintBoard()
{
foreach ( var str in answer[1])
{
foreach ( var letter in str)
Console.Write(letter + " " );
Console.WriteLine();
}
}
static bool Safe( int row, int col, List< string > board)
{
for ( int i = 0; i < board.Count; i++) {
if (board[i][col] == 'Q' )
return false ;
}
int x = row, y = col;
while (x >= 0 && y >= 0)
if (board[x--][y--] == 'Q' )
return false ;
x = row;
y = col;
while (x >= 0 && y < board.Count)
if (board[x--][y++] == 'Q' )
return false ;
return true ;
}
static void Rec(List< string > board, int row)
{
if (row == board.Count) {
answer.Add( new List< string >(board));
return ;
}
for ( int i = 0; i < board.Count; i++) {
if (Safe(row, i, board)) {
char [] rowArr = board[row].ToCharArray();
rowArr[i] = 'Q' ;
board[row] = new string (rowArr);
Rec(board, row + 1);
rowArr[i] = '.' ;
board[row] = new string (rowArr);
}
}
}
static List<List< string > > SolveNQueens( int n)
{
string s = "" ;
for ( int i = 0; i < n; i++)
s += '.' ;
List< string > board = new List< string >();
for ( int i = 0; i < n; i++)
board.Add(s);
Rec(board, 0);
return answer;
}
static void Main( string [] args)
{
Console.WriteLine(SolveNQueens(4).Count);
Console.WriteLine( "Out of " + answer.Count
+ " solutions one is following" );
PrintBoard();
}
}
}
|
Javascript
let answer = [];
function print_board() {
for (let str of answer[1]) {
for (let letter of str) console.log(letter + ' ' );
console.log( '\n' );
}
}
function safe(row, col, board) {
for (let i = 0; i < board.length; i++) {
if (board[i][col] == 'Q' ) return false ;
}
let i = row,
j = col;
while (i >= 0 && j >= 0) if (board[i--][j--] == 'Q' ) return false ;
i = row;
j = col;
while (i >= 0 && j < board.length) if (board[i--][j++] == 'Q' ) return false ;
return true ;
}
function rec(board, row) {
if (row == board.length) {
answer.push([...board]);
return ;
}
for (let i = 0; i < board.length; i++) {
if (safe(row, i, board)) {
board[row] = board[row].substring(0, i) + 'Q' + board[row].substring(i + 1);
rec(board, row + 1);
board[row] = board[row].substring(0, i) + '.' + board[row].substring(i + 1);
}
}
}
function solveNQueens(n) {
let board = new Array(n).fill( new Array(n).fill( '.' ).join( '' ));
rec(board, 0);
return answer;
}
console.log(solveNQueens(4).length);
console.log(`Out of ${answer.length} solutions, one is following:`);
print_board();
|
Output2
Out of 2 solutions one is following
. . Q .
Q . . .
. . . Q
. Q . .
Time Complexity: O(N!)
Auxiliary Space: O(N2)
Optimization in is_safe() function:
The idea is not to check every element in the right and left diagonal, instead use the property of diagonals:
- The sum of i and j is constant and unique for each right diagonal, where i is the row of elements and j is the
column of elements. - The difference between i and j is constant and unique for each left diagonal, where i and j are row and column of element respectively.
Below is the implementation of the Backtracking solution(with optimization):
C++
#include <bits/stdc++.h>
using namespace std;
#define N 4
int ld[30] = { 0 };
int rd[30] = { 0 };
int cl[30] = { 0 };
void printSolution( int board[N][N])
{
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < N; j++)
cout << " " << board[i][j] << " " ;
cout << endl;
}
}
bool solveNQUtil( int board[N][N], int col)
{
if (col >= N)
return true ;
for ( int i = 0; i < N; i++) {
if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1)
&& cl[i] != 1) {
board[i][col] = 1;
ld[i - col + N - 1] = rd[i + col] = cl[i] = 1;
if (solveNQUtil(board, col + 1))
return true ;
board[i][col] = 0;
ld[i - col + N - 1] = rd[i + col] = cl[i] = 0;
}
}
return false ;
}
bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == false ) {
cout << "Solution does not exist" ;
return false ;
}
printSolution(board);
return true ;
}
int main()
{
solveNQ();
return 0;
}
|
Java
import java.util.*;
class GFG {
static int N = 4 ;
static int [] ld = new int [ 30 ];
static int [] rd = new int [ 30 ];
static int [] cl = new int [ 30 ];
static void printSolution( int board[][])
{
for ( int i = 0 ; i < N; i++) {
for ( int j = 0 ; j < N; j++)
System.out.printf( " %d " , board[i][j]);
System.out.printf( "\n" );
}
}
static boolean solveNQUtil( int board[][], int col)
{
if (col >= N)
return true ;
for ( int i = 0 ; i < N; i++) {
if ((ld[i - col + N - 1 ] != 1
&& rd[i + col] != 1 )
&& cl[i] != 1 ) {
board[i][col] = 1 ;
ld[i - col + N - 1 ] = rd[i + col] = cl[i]
= 1 ;
if (solveNQUtil(board, col + 1 ))
return true ;
board[i][col] = 0 ;
ld[i - col + N - 1 ] = rd[i + col] = cl[i]
= 0 ;
}
}
return false ;
}
static boolean solveNQ()
{
int board[][] = { { 0 , 0 , 0 , 0 },
{ 0 , 0 , 0 , 0 },
{ 0 , 0 , 0 , 0 },
{ 0 , 0 , 0 , 0 } };
if (solveNQUtil(board, 0 ) == false ) {
System.out.printf( "Solution does not exist" );
return false ;
}
printSolution(board);
return true ;
}
public static void main(String[] args)
{
solveNQ();
}
}
|
Python3
N = 4
ld = [ 0 ] * 30
rd = [ 0 ] * 30
cl = [ 0 ] * 30
def printSolution(board):
for i in range (N):
for j in range (N):
print (board[i][j], end = " " )
print ()
def solveNQUtil(board, col):
if (col > = N):
return True
for i in range (N):
if ((ld[i - col + N - 1 ] ! = 1 and
rd[i + col] ! = 1 ) and cl[i] ! = 1 ):
board[i][col] = 1
ld[i - col + N - 1 ] = rd[i + col] = cl[i] = 1
if (solveNQUtil(board, col + 1 )):
return True
board[i][col] = 0
ld[i - col + N - 1 ] = rd[i + col] = cl[i] = 0
return False
def solveNQ():
board = [[ 0 , 0 , 0 , 0 ],
[ 0 , 0 , 0 , 0 ],
[ 0 , 0 , 0 , 0 ],
[ 0 , 0 , 0 , 0 ]]
if (solveNQUtil(board, 0 ) = = False ):
printf( "Solution does not exist" )
return False
printSolution(board)
return True
if __name__ = = '__main__' :
solveNQ()
|
C#
using System;
class GFG {
static int N = 4;
static int [] ld = new int [30];
static int [] rd = new int [30];
static int [] cl = new int [30];
static void printSolution( int [, ] board)
{
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < N; j++)
Console.Write( " {0} " , board[i, j]);
Console.Write( "\n" );
}
}
static bool solveNQUtil( int [, ] board, int col)
{
if (col >= N)
return true ;
for ( int i = 0; i < N; i++) {
if ((ld[i - col + N - 1] != 1
&& rd[i + col] != 1)
&& cl[i] != 1) {
board[i, col] = 1;
ld[i - col + N - 1] = rd[i + col] = cl[i]
= 1;
if (solveNQUtil(board, col + 1))
return true ;
board[i, col] = 0;
ld[i - col + N - 1] = rd[i + col] = cl[i]
= 0;
}
}
return false ;
}
static bool solveNQ()
{
int [, ] board = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == false ) {
Console.Write( "Solution does not exist" );
return false ;
}
printSolution(board);
return true ;
}
public static void Main(String[] args)
{
solveNQ();
}
}
|
Javascript
<script>
let N = 4;
let ld = new Array(30);
let rd = new Array(30);
let cl = new Array(30);
function printSolution( board)
{
for (let i = 0; i < N; i++)
{
for (let j = 0; j < N; j++)
document.write(board[i][j] + " " );
document.write( "<br/>" );
}
}
function solveNQUtil(board, col)
{
if (col >= N)
return true ;
for (let i = 0; i < N; i++)
{
if ((ld[i - col + N - 1] != 1 &&
rd[i + col] != 1) && cl[i] != 1)
{
board[i][col] = 1;
ld[i - col + N - 1] =
rd[i + col] = cl[i] = 1;
if (solveNQUtil(board, col + 1))
return true ;
board[i][col] = 0;
ld[i - col + N - 1] =
rd[i + col] = cl[i] = 0;
}
}
return false ;
}
function solveNQ()
{
let board = [[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ]];
if (solveNQUtil(board, 0) == false )
{
document.write( "Solution does not exist" );
return false ;
}
printSolution(board);
return true ;
}
solveNQ();
</script>
|
Output 0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
Time Complexity: O(N!)
Auxiliary Space: O(N)
Related Articles:
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.