Experiment No: 8 Experiment Name: Solving N-Queens Problem Using Back-Tracking Method. Code

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Experiment No: 8

Experiment name: Solving N-Queens problem using Back-Tracking method.

Code:

#include<bits/stdc++.h>

using namespace std;

int ROW[100000];//OUTPUT ARRAY SHOWED FOR N-QUEENS

bool issafe (int r, int c) { //check to set a queen in (r,c) position

for (int j = 1; j < r; j++) { //iterate every pre-set Queen

if (abs (ROW[j] - c) == abs (r - j) || c == ROW[j]) { //diagonal condition (|j-


l|==|i-k|) & column condition

return false; //if invalid

return true; //if valid

void PRINT_SOLUTION (int N) { //show Solution

printf ("Solution:");

for (int i = 1; i <= N; i++) //for every ROW


printf (" %d", ROW[i]); //print the safe position

printf ("\n");

void PRINT_BACKTRACK(int r, int c) { //show backtracking node

printf ("BACKTRACK FROM THE NODE MUSA:");

for (int i = 1; i < r; i++) //from 1 to (r-1)th ROW

printf (" %d", ROW[i]); //show previously set positions

printf (" %d\n", c); //show last position which is not safe

void NQ (int r, int N) { //function to solve N-Queens Problem

for (int c = 1; c <= N; c++) { //check for every column from 1 to N

if (issafe (r, c) ) { //check validity to set a Queen in (r,c) position

ROW[r] = c;//set a Queen in the (r,c) position safely

//printf ("ROW[%d]=%d\n", r, c);

/*breaking condition to find a solution*/

if (r == N) {

PRINT_SOLUTION (N); //print the ans

//if breaking condition not found

else {
NQ (r + 1, N); //recursively call NQ for (r+1)-th ROW

/*Backtracking Point Print

When cannot set a Queen safely*/

else {

PRINT_BACKTRACK(r, c);

int main() {

int N; //int for no. of Queens

scanf ("%d", &N); //INPUT no. of Queens

NQ (1, N); //NQ FUNCTION CALLED

return 0;

Output:

You might also like