0% found this document useful (0 votes)
2 views

alg5

The document presents a C program that solves the N Queens problem using backtracking. It defines functions to check if a queen can be placed safely on the board and to recursively attempt to place queens in valid positions. The program prompts the user for the size of the board (N) and outputs a solution if one exists.

Uploaded by

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

alg5

The document presents a C program that solves the N Queens problem using backtracking. It defines functions to check if a queen can be placed safely on the board and to recursively attempt to place queens in valid positions. The program prompts the user for the size of the board (N) and outputs a solution if one exists.

Uploaded by

astrophileion369
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

EX.13: ‘N’ QUEENS PROBLEM USING BACKTRACKING.

PROGRAM:
#include <stdio.h>
#include <conio.h>
#define MAX 100
int board[MAX][MAX];
void printSolution(int N) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", board[i][j]);
}
printf("\n");
}
}int isSafe(int row, int col, int N) {
int i, j;
for (i = 0; i < col; i++) {
if (board[row][i] == 1) {
return 0;
}
}
for (i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 1) {
return 0;
}
}
for (i = row, j = col; j >= 0 && i < N; i++, j--) {
if (board[i][j] == 1) {
return 0;
}
}
return 1;
}
int solveNQueens(int N, int col) {
if (col >= N) {
return 1;
}
for (int i = 0; i < N; i++) {
if (isSafe(i, col, N)) {
board[i][col] = 1;
if (solveNQueens(N, col + 1)) {
return 1;
}
board[i][col] = 0;
}
}
return 0;
}
int main() {
int N;
printf("Enter the value of N: ");
scanf("%d", &N);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
board[i][j] = 0;
}
}if (solveNQueens(N, 0)) {
printf("Solution exists:\n");
printSolution(N);
} else {
printf("No solution exists\n");
}
getch();
return 0;
}

OUTPUT:
Enter the value of N: 4

Solution exists:
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0

You might also like