C program for n-Queen's problem using backtracking

This page has a C program for n-Queen's problem using backtracking. It is clear that, this C program will implement the n-Queen's problem using backtracking. For example: In the chess game, a queen can move as hor­i­zon­tally, ver­ti­cally, or diag­o­nally. That is, a chess board contains 8 rows and 8 columns. In this standard 8 x 8 size chess board, 8 by 8 Queen’s prob­lem asks that how to place the 8 queens on the ordi­nary chess board(8 x 8 size) so that no can hit any other in one move. The below given C program is used to implement the n-Queen's problem using backtracking. Kindly check out the program to implement the n-Queen's problem using backtracking.

How will ask n-Queen's problem

The Questions for n-Queen's problem can be asked as . . . 1). C Program for N Queens Problem Using Backtracking. 2). C Program Solution for N-Queens Problem. 3). C program for n Queens Backtracking algorithm. 4). C program for n Queens problem using Backtracking algorithm. 5). Program for N Queens Problem in C Using Backtracking. 6). C Progran to Implement N Queen's Problem using Backtracking. 7). C Program of N Queens Problem Solution using Backtracking. 8). C Program for N Queens Problem Algorithm using Backtracking.

n- Queen 's problem using backtracking Program

#include<stdio.h>

#include<math.h>

void putnqueen(int);

int okqueen(int, int);

int setqueen(int);

void queen();

char p[10][10];

int n;

int main() {

int a, b;

clrscr();

printf(" Enter the no. of queens : ");

scanf("%d", &n);

for (a = 0; a < n; ++a)

for (b = 0; b < n; ++b)

p[a][b] = '.';

putnqueen(0);

getch();

return (0);

}

void putnqueen(int x) {

int a;

if (x < n) {

for (a = 0; a < n; ++a) {

if (okqueen(x, a)) {

p[x][a] = 'Q';

putnqueen(x + 1);

p[x][a] = '.';

}

}

} else {

printf("

The solution is ");

queen();

}

}

int okqueen(int x, int y) {

int a, b;

for (a = 0; a < n; ++a) {

b = setqueen(a);

if (y == b || abs(x - a) == abs(y - b))

return 0;

}

return 1;

}

int setqueen(int x) {

int a;

for (a = 0; a < n; ++a)

if (p[x][a] == 'Q') {

return(a);

break;

}

}

void queen(){

int a, b;

printf("

");

for (a = 0; a < n; ++a) {

for (b = 0; b < n; ++b)

printf("\t%c", p[a][b]);

printf("



");

}

} Sample Output: Enter the no. of queens : 4



The solution is

. Q . .



. . . Q



Q . . .



. . Q .





The solution is

. . Q .



Q . . .



. . . Q



. Q . .

Related Popular Posts: