hi i need help in my code I'm facing problem how can i make a condition to make to queen can only be in specific coordinate and all other coordinate is vailed i have 8 colum and 8 rows and here is my code
also when the user input the first colum and row the program will display the answer then exit its not going to ask other question for new row and colum it should ask the user for 8 rows and colum the vailed once are in the solution other should be invailed
the code is here
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#define N 8
void Color(int col) {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, col);
}
int brd[][8]=
{ { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0} ,
{ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0} ,
{ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0} ,
{ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0} ,
{ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0} ,
{ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0} ,
{ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0},
{ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0}
};
void printSolution(int board[N][N]) {
int queen[0];
printf("Enter the queen location in row : ");
scanf("%d",&queen[0]);
queen[0] = queen[0] - 1;
printf("Enter the queen location in colum : ");
scanf("%d",&queen[1]);
queen[1] = queen[1] - 1;
if (queen[0]>7)
{
printf("invailed location\n");return;
}
if (queen[1] <0){
printf("invailed location\n");return;
}
else {
printf("%d %d \n", queen[0], queen[1]);
brd[queen[0]][queen[1]] = 1;
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (brd[i][j] == 1) {
Color(2);
printf("%d ", brd[i][j]);
} else {
Color(15);
printf("%d ", brd[i][j]);
}
}
printf("\n");
board[queen[0]][queen[1]] = 1;
}
printf("the correct solution :\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (board[i][j] == 1) {
Color(2);
printf("%d ", board[i][j]);
} else {
Color(15);
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 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();
_getch();
return 0;
}
What I have tried:
tried different method nothing working with me please test the code and try to solve this for me