-
Notifications
You must be signed in to change notification settings - Fork 0
/
queens1.c
83 lines (73 loc) · 1.63 KB
/
queens1.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <stdio.h>
#define N 5
void printBoard(int board[N][N]);
int isSafe(int board[N][N], int row, int col);
int placeQueen(int board[N][N], int row, int col);
int main()
{
int board[N][N] = {0};
int row, col, queensPlaced = 0;
while (queensPlaced < N)
{
printBoard(board);
printf("Enter row and column to place a queen (0-indexed): ");
scanf("%d %d", &row, &col);
if (placeQueen(board, row, col))
{
queensPlaced++;
}
else
{
printf("Invalid position! Try again.\n");
}
}
printBoard(board);
printf("All queens placed successfully!\n");
return 0;
}
void printBoard(int board[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (board[i][j] == 0)
printf("|_");
else
printf("|♛");
}
printf("|\n");
}
printf("\n");
}
int isSafe(int board[N][N], int row, int col)
{
// Check the row and column
for (int i = 0; i < N; i++)
{
if (board[row][i] || board[i][col])
return 0;
}
// Check the diagonals
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (i + j == row + col || i - j == row - col)
{
if (board[i][j])
return 0;
}
}
}
return 1;
}
int placeQueen(int board[N][N], int row, int col)
{
if (row >= 0 && row < N && col >= 0 && col < N && isSafe(board, row, col))
{
board[row][col] = 1;
return 1;
}
return 0;
}