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

4/30/24, 12:11 PM N-Queens: Attempt review

Dashboard / My courses / CB19541-AAD-2022 / Backtracking / N-Queens

Started on Monday, 29 April 2024, 9:40 PM


State Finished
Completed on Monday, 29 April 2024, 9:44 PM
Time taken 4 mins 47 secs
Marks 1.00/1.00
Grade 10.00 out of 10.00 (100%)
Name PRITHIV G 2022-CSBS-B

https://www.rajalakshmicolleges.net/moodle/mod/quiz/review.php?attempt=769894&cmid=6811 1/4
4/30/24, 12:11 PM N-Queens: Attempt review

Question 1

Correct

Mark 1.00 out of 1.00

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an
empty space, respectively.

Example 1:

Input:

Output:

.Q..
...Q

Q...

..Q.

Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above

Example 2:
Input:

Output:

Answer: (penalty regime: 0 %)


1 #include <stdio.h>
2
3 int N;
4 int board[100][100];
5
6 int isattack(int,int);
7 int nQueen(int);
8 void print();
9
10 ▼ int main() {
11 scanf("%d", &N);
12 int i,j;
13 ▼ for(i=0; i<N; i++) {
14 ▼ for(j=0; j<N; j++) {
15 board[i][j] = 0; 
16 }
https://www.rajalakshmicolleges.net/moodle/mod/quiz/review.php?attempt=769894&cmid=6811 2/4
4/30/24, 12:11 PM N-Queens: Attempt review
}
17 }
18 if (nQueen(N))
19 print();
20 return 0;
21 }
22
23 ▼ int nQueen(int n) {
24 int i,j;
25 if(n==0)
26 return 1;
27
28 ▼ for(i=0; i<N; i++) {
29 ▼ for(j=0; j<N; j++) {
30 ▼ if(!(isattack(i,j)) && (board[i][j] != 1) ) {
31 board[i][j] = 1;
32 ▼ if(nQueen(n-1)==1) {
33 return 1;
34 }
35 board[i][j] = 0;
36 }
37 }
38 }
39 return 0;
40 }
41
42 ▼ int isattack(int i, int j) {
43 int k,l;
44 ▼ for(k=0; k<N; k++) {
45 ▼ if((board[i][k] == 1) || (board[k][j] ==1)) {
46 return 1;
47 }
48 }
49
50 ▼ for(k=0; k<N; k++) {
51 ▼ for(l=0; l<N; l++) {
52 ▼ if((k-l)==(i-j) || (k+l)==(i+j)) {
53 ▼ if(board[k][l]==1) {
54 return 1;
55 }
56 }
57 }
58 }
59 return 0;
60 }
61
62 ▼ void print() {
63 int i, j;
64 ▼ for(i=0; i<N; i++) {
65 ▼ for(j=0; j<N; j++) {
66 ▼ if(board[i][j]==1) {
67 printf("Q");
68 }
69 else
70 printf(".");
71 }
72 printf("\n");
73 }
74 }
75

Input Expected Got

 4 .Q.. .Q.. 
...Q ...Q
Q... Q...
..Q. ..Q.

https://www.rajalakshmicolleges.net/moodle/mod/quiz/review.php?attempt=769894&cmid=6811 3/4
4/30/24, 12:11 PM N-Queens: Attempt review

Input Expected Got

 1 Q Q 

Passed all tests! 

Correct
Marks for this submission: 1.00/1.00.

◄ Removing Chocolates

Jump to...

Sum of All Subset XOR Totals ►

https://www.rajalakshmicolleges.net/moodle/mod/quiz/review.php?attempt=769894&cmid=6811 4/4

You might also like