Advertisement
dlackovi2

n kraljica sa ispisom koordinata i svih solucija

Jan 13th, 2015
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. # include <stdio.h>
  2. # include <stdlib.h>
  3. # include <time.h>
  4.  
  5.  
  6. int N; //For N * N ChessBoard
  7. int flag;
  8. void printArray(int a[]); /* Just to Print the Final Solution */
  9. void getPositions(int a[],int n1,int n2); /* The Recursive Function */
  10.  
  11. int main()
  12. {
  13.  
  14. int *a;
  15. int ctr=0;
  16. printf("\nTHE N QUEENS PROBLEM ");
  17. printf("\nNumber Of Rows(N) For NxN Chessboard.");
  18. scanf("%d",&N);
  19. a=(int *)(malloc(sizeof(int)*N));
  20. printf("\nAll possible Solutions .. \n");
  21. printf("\nIn Each of the solutions the Coordinates of the N-Queens are given (Row,Col) .");
  22. printf("\nNote that the Rows and Colums are numbered between 1 - N :\n");
  23. for(ctr=0;ctr<N;ctr++)
  24. getPositions(a,0,ctr);
  25. getchar();
  26. getchar();
  27. }
  28.  
  29. void printArray(int a[])
  30. {
  31. int i,choice;
  32. static int counter=0;
  33. counter++;
  34. printf("\nSOLUTION # %d :",counter);
  35. for(i=0;i<N;i++)
  36. printf("(%d,%d) ",i+1,a[i]+1);
  37. if(counter%10==0) { printf("\nEnter 0 to exit , 1 to continue .");
  38. scanf("%d",&choice);
  39. if(choice==0) exit(0);
  40. };
  41. }
  42. void getPositions(int a1[],int colno,int val)
  43. { int ctr1,ctr2;
  44. a1[colno]=val;
  45. if(colno==N-1)
  46. { printArray(a1) ; return;
  47. };
  48. for(ctr1=0;ctr1<N;)
  49. { /* This Loop Finds Suitable Column Numbers , in the NEXT ROW */
  50. for(ctr2=0;ctr2<=colno;ctr2++)
  51. if(a1[ctr2]==ctr1 || (colno+1-ctr2)*(colno+1-ctr2)==(ctr1-a1[ctr2])*(ctr1-a1[ctr2]))
  52. goto miss1;
  53. getPositions(a1,colno+1,ctr1);
  54. miss1:
  55. ctr1++;
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement