Loading…
DAA · Backtracking & B&B · Program 18 · In the record
Write a program in c to solve the N-Queen problem using backtracking and find its execution time using the time function.
Algorithm: Place(k, i) (returns true if a queen can be placed in row k, column i) 1. For j <- 1 to (k-1) do 2. if x[j] == i or |x[j] - i| == |j - k| then 3. Return false 4. Return true Algorithm: NQueens(k, n) 1. Start 2. For i <- 1 to n do 3. if Place(k, i) then 4. x[k] <- i 5. if k == n then 6. print x[1..n] 7. else 8. NQueens(k+1, n) 9. Stop
1#include<stdio.h>2#include<time.h>3 4int x[20],first[20];5int n,solutions=0,comp=0;6 7int place(int k,int i) {8 int j;9 for(j=1;j<k;j++) {10 comp++;11 if(x[j]==i || x[j]-i==j-k || x[j]-i==k-j)12 return 0;13 }14 return 1;15}16 17void nQueens(int k) {18 int i,j;19 for(i=1;i<=n;i++) {20 if(place(k,i)) {21 x[k]=i;22 if(k==n) {23 solutions++;24 printf("\nSolution %d:",solutions);25 for(j=1;j<=n;j++)26 printf("\t%d",x[j]);27 if(solutions==1)28 for(j=1;j<=n;j++)29 first[j]=x[j];30 }31 else32 nQueens(k+1);33 }34 }35}36 37int main() {38 int i,j;39 printf("Enter the number of queens:");40 scanf("%d",&n);41 42 printf("\nColumn of the queen in each row 1..%d:",n);43 clock_t start=clock();44 nQueens(1);45 clock_t end=clock();46 double time_taken=(double)(end-start)/CLOCKS_PER_SEC;47 48 if(solutions>0) {49 printf("\n\nBoard for solution 1:");50 for(i=1;i<=n;i++) {51 printf("\n");52 for(j=1;j<=n;j++)53 if(first[i]==j)54 printf("Q ");55 else56 printf(". ");57 }58 }59 printf("\nTotal solutions:%d",solutions);60 printf("\nNumber of comparisons:%d",comp);61 printf("\nTime taken:%f seconds",time_taken);62 printf("\nTime complexity: O(n!)");63 printf("\nSpace complexity: O(n)");64 printf("\n");65 return 0;66}4Enter the number of queens:4 Column of the queen in each row 1..4: Solution 1: 2 4 1 3 Solution 2: 3 1 4 2 Board for solution 1: . Q . . . . . Q Q . . . . . Q . Total solutions:2 Number of comparisons:84 Time taken:0.000008 seconds Time complexity: O(n!) Space complexity: O(n)
Run program 18 in your browser
C · clang → WebAssembly. Change the code or the input, run it, break it, and see what happens.