How To Solve For N
We have discussed Knight'south tour and Rat in a Maze problem in Set 1 and Fix ii respectively. Let us discuss N Queen as another example trouble that can exist solved using backtracking.
The N Queen is the problem of placing Northward 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.
The expected output is a binary matrix that has 1s for the blocks where queens are placed. For example, the following is the output matrix for the higher up 4 queen solution.
{ 0, 1, 0, 0}
{ 0, 0, 0, 1}
{ 1, 0, 0, 0}
{ 0, 0, ane, 0}
Naive Algorithm
Generate all possible configurations of queens on board and impress a configuration that satisfies the given constraints.
while in that location are untried configurations { generate the next configuration if queens don't attack in this configuration then { impress this configuration; } } Backtracking Algorithm
The idea is to place queens one by one in unlike columns, starting from the leftmost cavalcade. When we identify a queen in a column, we check for clashes with already placed queens. In the current cavalcade, if we observe a row for which there is no clash, we mark this row and column as part of the solution. If we do non find such a row due to clashes, then we backtrack and return false.
ane) Start in the leftmost column two) If all queens are placed return true 3) Endeavor all rows in the current column. Do post-obit for every tried row. a) If the queen tin exist placed safely in this row and then marking this [row, column] as office of the solution and recursively bank check if placing queen here leads to a solution. b) If placing the queen in [row, column] leads to a solution then return true. c) If placing queen doesn't atomic number 82 to a solution so unmark this [row, column] (Backtrack) and go to stride (a) to endeavour other rows. 4) If all rows have been tried and nothing worked, render simulated to trigger backtracking.
Implementation of Backtracking solution
C++
#include <bits/stdc++.h>
#define N 4
using namespace std;
void printSolution( int lath[N][N])
{
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < N; j++)
cout << " " << board[i][j] << " " ;
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 faux ;
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 (lath[i][j])
return false ;
return true ;
}
bool solveNQUtil( int board[Northward][N], int col)
{
if (col >= Northward)
render truthful ;
for ( int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1;
if (solveNQUtil(board, col + 1))
render truthful ;
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(lath, 0) == false ) {
cout << "Solution does not be" ;
return faux ;
}
printSolution(board);
return true ;
}
int primary()
{
solveNQ();
render 0;
}
C
#define N four
#include <stdbool.h>
#include <stdio.h>
void printSolution( int lath[Northward][Northward])
{
for ( int i = 0; i < North; i++) {
for ( int j = 0; j < N; j++)
printf ( " %d " , board[i][j]);
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 faux ;
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (lath[i][j])
return false ;
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return simulated ;
render true ;
}
bool solveNQUtil( int board[North][North], int col)
{
if (col >= N)
render true ;
for ( int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1;
if (solveNQUtil(board, col + 1))
return truthful ;
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) == fake ) {
printf ( "Solution does not be" );
render false ;
}
printSolution(board);
return truthful ;
}
int main()
{
solveNQ();
return 0;
}
Java
public class NQueenProblem {
final int N = iv ;
void printSolution( int board[][])
{
for ( int i = 0 ; i < N; i++) {
for ( int j = 0 ; j < N; j++)
Organisation.out.impress( " " + board[i][j]
+ " " );
System.out.println();
}
}
boolean isSafe( int board[][], int row, int col)
{
int i, j;
for (i = 0 ; i < col; i++)
if (board[row][i] == i )
return false ;
for (i = row, j = col; i >= 0 && j >= 0 ; i--, j--)
if (board[i][j] == i )
return false ;
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (lath[i][j] == i )
return false ;
return true ;
}
boolean solveNQUtil( int board[][], int col)
{
if (col >= North)
return true ;
for ( int i = 0 ; i < Northward; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1 ;
if (solveNQUtil(board, col + one ) == true )
return truthful ;
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(lath, 0 ) == false ) {
Organization.out.print( "Solution does not be" );
return false ;
}
printSolution(board);
render true ;
}
public static void main(Cord 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):
print (lath[i][j], end = " " )
print ()
def isSafe(board, row, col):
for i in range (col):
if board[row][i] = = one :
return False
for i, j in zilch ( range (row, - one , - 1 ),
range (col, - one , - i )):
if board[i][j] = = 1 :
return Imitation
for i, j in zip ( range (row, North, 1 ),
range (col, - 1 , - one )):
if board[i][j] = = 1 :
render False
return Truthful
def solveNQUtil(board, col):
if col > = N:
render True
for i in range (Due north):
if isSafe(board, i, col):
board[i][col] = 1
if solveNQUtil(lath, col + 1 ) = = Truthful :
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 non exist" )
return Imitation
printSolution(board)
return True
solveNQ()
C#
using Organisation;
class GFG
{
readonly int N = four;
void printSolution( int [,]lath)
{
for ( int i = 0; i < N; i++)
{
for ( int j = 0; j < North; j++)
Console.Write( " " + board[i, j]
+ " " );
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 < Due north; i++, j--)
if (board[i, j] == 1)
return false ;
return true ;
}
bool solveNQUtil( int [,]board, int col)
{
if (col >= Due north)
return true ;
for ( int i = 0; i < N; i++)
{
if (isSafe(board, i, col))
{
board[i, col] = 1;
if (solveNQUtil(lath, col + 1) == true )
return true ;
lath[i, col] = 0;
}
}
render 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 fake ;
}
printSolution(board);
return truthful ;
}
public static void Main(Cord []args)
{
GFG Queen = new GFG();
Queen.solveNQ();
}
}
Javascript
<script>
const N = iv
function printSolution(lath)
{
for (let i = 0; i < North; i++)
{
for (let j = 0; j < N; j++)
{
document.write(board[i][j], " " )
}
document.write( "</br>" )
}
}
office isSafe(lath, row, col)
{
for (let i = 0; i < col; i++){
if (board[row][i] == ane)
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 truthful
}
function solveNQUtil(board, col){
if (col >= N)
return true
for (allow i=0;i<N;i++){
if (isSafe(board, i, col)== true ){
board[i][col] = ane
if (solveNQUtil(lath, col + 1) == true )
return true
board[i][col] = 0
}
}
render false
}
role solveNQ(){
allow 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 non exist" )
return false
}
printSolution(lath)
return true
}
solveNQ()
</script>
Output
0 0 1 0 one 0 0 0 0 0 0 1 0 1 0 0
Time Complexity: O(N!)
Auxiliary Space: O(N2)
Optimization in is_safe() role
The idea is not to check every element in right and left diagonal, instead utilise the property of diagonals:
1. 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.
2. The deviation betwixt i and j is constant and unique for each left diagonal, where i and j are row and column of element respectively.
Implementation of Backtracking solution(with optimization)
C++
#include<bits/stdc++.h>
using namespace std;
#define N 4
int ld[xxx] = { 0 };
int rd[xxx] = { 0 };
int cl[xxx] = { 0 };
void printSolution( int board[N][North])
{
for ( int i = 0; i < Due north; i++) {
for ( int j = 0; j < Northward; j++)
cout<< " " << board[i][j]<< " " ;
cout<<endl;
}
}
bool solveNQUtil( int board[Due north][Northward], int col)
{
if (col >= N)
return true ;
for ( int i = 0; i < N; i++) {
if ((ld[i - col + North - i] != ane && rd[i + col] != 1) && cl[i] != 1) {
board[i][col] = 1;
ld[i - col + N - one] = rd[i + col] = cl[i] = 1;
if (solveNQUtil(board, col + 1))
return true ;
lath[i][col] = 0;
ld[i - col + N - 1] = rd[i + col] = cl[i] = 0;
}
}
render false ;
}
bool solveNQ()
{
int lath[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 non exist" ;
return false ;
}
printSolution(board);
render true ;
}
int principal()
{
solveNQ();
return 0;
}
C
#define N 4
#include <stdbool.h>
#include <stdio.h>
void printSolution( int board[N][North])
{
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < Northward; j++)
printf ( " %d " , board[i][j]);
printf ( "\n" );
}
}
bool isSafe( int board[Northward][N], int row, int col)
{
int i, j;
for (i = 0; i < col; i++)
if (lath[row][i])
return fake ;
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return faux ;
for (i = row, j = col; j >= 0 && i < Northward; i++, j--)
if (board[i][j])
return simulated ;
return truthful ;
}
bool solveNQUtil( int lath[N][Northward], int col)
{
if (col >= N)
return true ;
for ( int i = 0; i < Due north; i++) {
if (isSafe(board, i, col)) {
board[i][col] = one;
if (solveNQUtil(board, col + 1))
return true ;
board[i][col] = 0;
}
}
return false ;
}
bool solveNQ()
{
int lath[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == fake ) {
printf ( "Solution does non be" );
return faux ;
}
printSolution(board);
return truthful ;
}
int primary()
{
solveNQ();
return 0;
}
Java
import java.util.*;
class GFG
{
static int Northward = 4 ;
static int []ld = new int [ xxx ];
static int []rd = new int [ 30 ];
static int []cl = new int [ 30 ];
static void printSolution( int lath[][])
{
for ( int i = 0 ; i < N; i++)
{
for ( int j = 0 ; j < North; 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 < Northward; i++)
{
if ((ld[i - col + N - one ] != one &&
rd[i + col] != 1 ) && cl[i] != 1 )
{
board[i][col] = one ;
ld[i - col + N - one ] =
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 non exist" );
return fake ;
}
printSolution(lath);
render true ;
}
public static void main(String[] args)
{
solveNQ();
}
}
Python3
N = four
ld = [ 0 ] * xxx
rd = [ 0 ] * thirty
cl = [ 0 ] * 30
def printSolution(board):
for i in range (N):
for j in range (N):
impress (board[i][j], end = " " )
print ()
def solveNQUtil(board, col):
if (col > = N):
return Truthful
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 )):
render Truthful
lath[i][col] = 0
ld[i - col + Northward - 1 ] = rd[i + col] = cl[i] = 0
return Fake
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 be" )
return False
printSolution(board)
return True
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 < North; i++)
{
for ( int j = 0; j < Northward; j++)
Console.Write( " {0} " , lath[i, j]);
Console.Write( "\n" );
}
}
static bool solveNQUtil( int [,]board, int col)
{
if (col >= Due north)
return truthful ;
for ( int i = 0; i < North; i++)
{
if ((ld[i - col + Northward - ane] != 1 &&
rd[i + col] != one) && cl[i] != 1)
{
board[i, col] = 1;
ld[i - col + N - 1] =
rd[i + col] = cl[i] = 1;
if (solveNQUtil(lath, col + one))
return truthful ;
lath[i, col] = 0;
ld[i - col + N - 1] =
rd[i + col] = cl[i] = 0;
}
}
return false ;
}
static bool solveNQ()
{
int [,]lath = {{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 }};
if (solveNQUtil(board, 0) == imitation )
{
Console.Write( "Solution does not exist" );
return fake ;
}
printSolution(board);
render true ;
}
public static void Chief(String[] args)
{
solveNQ();
}
}
Javascript
<script>
let North = iv;
allow ld = new Assortment(30);
allow rd = new Array(30);
let cl = new Array(thirty);
function printSolution( lath)
{
for (permit i = 0; i < N; i++)
{
for (permit j = 0; j < Due north; j++)
certificate.write(board[i][j] + " " );
document.write( "<br/>" );
}
}
function solveNQUtil(board, col)
{
if (col >= N)
return true ;
for (allow i = 0; i < Northward; i++)
{
if ((ld[i - col + N - 1] != one &&
rd[i + col] != one) && cl[i] != 1)
{
board[i][col] = i;
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 - one] =
rd[i + col] = cl[i] = 0;
}
}
render false ;
}
role solveNQ()
{
let lath = [[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0 ]];
if (solveNQUtil(lath, 0) == imitation )
{
document.write( "Solution does not be" );
return false ;
}
printSolution(board);
render true ;
}
solveNQ();
</script>
Output
0 0 1 0 1 0 0 0 0 0 0 1 0 1 0 0
Fourth dimension Complication: O(N!)
Auxiliary Space: O(N)
Printing all solutions in Due north-Queen Problem
Sources:
http://see.stanford.edu/materials/icspacs106b/H19-RecBacktrackExamples.pdf
http://en.literateprograms.org/Eight_queens_puzzle_%28C%29
http://en.wikipedia.org/wiki/Eight_queens_puzzle
Please write comments if you find anything wrong, or you desire to share more than information well-nigh the topic discussed in a higher place.
How To Solve For N,
Source: https://www.geeksforgeeks.org/n-queen-problem-backtracking-3/
Posted by: calhoonvandice.blogspot.com

0 Response to "How To Solve For N"
Post a Comment