SHARE
TWEET

uvaBackToThe8Queen_____unsoloved

islam2366 Apr 22nd, 2019 98 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #define SIZE 8
  3. int Case;
  4. int Board[SIZE][SIZE];
  5. int Input[SIZE];
  6. int Queens[92][SIZE];
  7. int k;
  8. int N;
  9. int Min;
  10. void processQueens()
  11. {
  12.     int i, j;
  13.     for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) {
  14.         if (1 == Board[i][j])
  15.             Queens[k][i] = j + 1;
  16.     }
  17.     k++;
  18. }
  19. int isSafe(int row, int col)
  20. {
  21.     int i, j;
  22.     for (i = 0; i < col; i++)
  23.         if (Board[row][i])
  24.             return 0;
  25.     for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
  26.         if (Board[i][j])
  27.             return 0;
  28.     for (i = row, j = col; j >= 0 && i < 8; i++, j--)
  29.         if (Board[i][j])
  30.             return 0;
  31.     return 1;
  32. }
  33. int solve(int col)
  34. {
  35.     int i;
  36.     if (col == 8) {
  37.         processQueens();
  38.         return 1;
  39.     }
  40.     int res = 0;
  41.     for (i = 0; i < 8; i++) {
  42.         if (isSafe(i, col)) {
  43.             Board[i][col] = 1;
  44.             res = solve(col + 1) || res;
  45.             Board[i][col] = 0;
  46.         }
  47.     }
  48.     return res;
  49. }
  50. int abs(int a)
  51. {
  52.     if (a < 0)
  53.         return a * -1;
  54.     return a;
  55. }
  56. void readCase()
  57. {
  58.     int i;
  59.     for (i = 1; i < 8; i++)
  60.         scanf("%d", &Input[i]);
  61. }
  62. void solveCase()
  63. {
  64.     k = 0;
  65.     Min = 10000000;
  66.     int i, j;
  67.     int dist;
  68.     for(i = 0 ; i< 92; i++) {
  69.         dist = 0;
  70.         for (j = 0; j < 8; j++) {
  71.             dist += abs(Input[j] - Queens[i][j]);
  72.         }
  73.         printf("Dist: %d\n", dist);
  74.         if (dist < Min)
  75.             Min = dist;
  76.     }
  77. }
  78. void printCase()
  79. {
  80.     Case++;
  81.     printf("Case %d: %d\n", Case, Min);
  82. }
  83. int main()
  84. {
  85.     freopen("input.txt", "r", stdin);
  86.     freopen("output.txt", "w", stdout);
  87.     solve(0);
  88.     Case = 0;
  89.     while (1 == scanf("%d", &Input[0])) {
  90.         readCase();
  91.         solveCase();
  92.         printCase();
  93.     }
  94.     return 0;
  95. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top