Advertisement
Guest User

Untitled

a guest
Feb 24th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int safe(char * config, int i, int j)
  6. {
  7. int r, s;
  8.  
  9. for (r = 0; r < i; r++)
  10. {
  11. s = config[r];
  12. if (j == s || i-r==j-s || i-r==s-j)
  13. return 0;
  14. }
  15. return 1;
  16. }
  17.  
  18. int count = 0;
  19.  
  20. void nqueens_serial(char *config, int n, int i)
  21. {
  22. char *new_config;
  23. int j;
  24.  
  25. if (i==n)
  26. {
  27. count++;
  28. }
  29.  
  30. for (j=0; j<n; j++)
  31. {
  32. new_config = malloc((i+1)*sizeof(char));
  33. memcpy(new_config, config, i*sizeof(char));
  34. if (safe(new_config, i, j))
  35. {
  36. new_config[i] = j;
  37. nqueens_serial(new_config, n, i+1);
  38. }
  39. free(new_config);
  40. }
  41. return;
  42. }
  43.  
  44. void nqueens(char *config, int n, int i)
  45. {
  46. char *new_config;
  47. int j;
  48.  
  49. if (i==n)
  50. {
  51. #pragma omp atomic
  52. count++;
  53. }
  54. for (j=0; j<n; j++)
  55. {
  56. if (i < 5){
  57. #pragma omp task
  58. {
  59. new_config = malloc((i+1)*sizeof(char));
  60. memcpy(new_config, config, i*sizeof(char));
  61. if (safe(new_config, i, j))
  62. {
  63. new_config[i] = j;
  64. nqueens(new_config, n, i+1);
  65. }
  66. free(new_config);
  67. }
  68. }else{
  69. new_config = malloc((i+1)*sizeof(char));
  70. memcpy(new_config, config, i*sizeof(char));
  71. if (safe(new_config, i, j))
  72. {
  73. new_config[i] = j;
  74. nqueens_serial(new_config, n, i+1);
  75. }
  76. free(new_config);
  77. }
  78. }
  79.  
  80. return;
  81. }
  82.  
  83.  
  84. int main(int argc, char *argv[])
  85. {
  86. int n;
  87. char *config;
  88.  
  89. if (argc < 2)
  90. {
  91. printf("%s: number of queens required\n", argv[0]);
  92. return 1;
  93. }
  94.  
  95. n = atoi(argv[1]);
  96. config = malloc(n * sizeof(char));
  97.  
  98. printf("running queens %d\n", n);
  99. #pragma omp parallel
  100. {
  101. #pragma omp single
  102. {
  103. nqueens(config, n, 0);
  104. }
  105. }
  106.  
  107. printf("# solutions: %d\n", count);
  108.  
  109. return 0;
  110. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement