Advertisement
juanjo12x

UVA_11085_Back_8_Queens

Apr 21st, 2014
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.09 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define min(a,b) a < b ? a:b;
  4. int queens[8];int path[8];
  5.  
  6. int valid (int r,int c){
  7.     int j;
  8.     for (j=0;j<r;j++){
  9.         if (c==path[j]) return 0;
  10.         if (abs(r-j)==abs(c-path[j])) return 0;
  11.     }
  12.     return 1;
  13. }
  14. int search(int n){
  15.     int i;
  16.     if (n==8) return 0;
  17.      int tot = 100000;
  18.     /*buscamos en cada fila*/
  19.     for (i=0;i<8;i++){
  20.         if (valid(n,i)){
  21.             path[n]=i;
  22.             if (i==queens[n]){
  23.                 tot=min(tot,search(n+1));
  24.             }else{
  25.                 tot=min(tot,1+search(n+1));
  26.             }
  27.            
  28.         }
  29.     }
  30.      return tot;
  31. }
  32. int main(int argc, char** argv) {
  33.     int i;int cont=1;
  34.     while (scanf("%d %d %d %d %d %d %d %d", &queens[0], &queens[1],
  35.             &queens[2], &queens[3], &queens[4], &queens[5], &queens[6],
  36.             &queens[7]) != EOF){
  37.         for (i=0;i<8;i++){
  38.             queens[i]=queens[i]-1;
  39.             path[i]=queens[i];
  40.            
  41.         }
  42.        
  43.          printf("Case %d: %d\n", cont, search(0));
  44.          cont++;
  45.     }
  46.     return (EXIT_SUCCESS);
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement