2012-07-25 2 views
0

이 코드를 실행할 때 터미널이 대부분 멈추지 만 때때로 해결책을 얻으려고합니다. 나는 이것이 퀸즈 퍼즐을 푸는 가장 좋은 방법이 아니라는 것을 알고 있습니다. 따라서 그것에 대해 언급하지 마십시오. 도움을받을 시간이있는 사람에게 감사드립니다. 이제까지는 법적으로 더 이상 여왕을 배치 할 수없는 지점에 도달하면 프로그램이 "역 추적"할 수 없기 때문에8 queens puzzle : 무작위 숫자를 사용하면 무한 루프가 발생합니다.

#include <stdio.h> 
#include <ctype.h> 
#include <stdlib.h> 
#include <string.h> 
#include <time.h> 

int check(int number, int arr[]){ 
    int num = 0; 
    int i; 
    for(i = 0; i < 8; i++){ 
     if(arr[i] == number) 
      num = 1; 
    } 

    return num; 
} 
int main(int argc, char * argv[]){ 
    srand(time(NULL)); 
    int r, r2, i, v; 
    char arr[8][8]; 
    int sum[8] = {0}; 
    int sum2[8] = {0}; 
    int row[8]; 
    int col[8]; 
    int cRow[8]; 
    int cCol[8]; 
    int count = 0; 
    int sums = 0; 
    int sums2 = 0; 

    //Fill arrays and 2d array. 
    for(i = 0; i < 8; i++){ 
     row[i] = 0; 
     col[i] = 0; 
     cRow[i] = 0; 
     cCol[i] = 0; 
     for(v = 0; v < 8; v++){ 
      arr[i][v] = '_'; 
     } 
    } 
    for(v = 0; v < 8; v++){ 
     sum[v] = 0; 
     sum2[v] = 0; 
     printf("%d", sum[v]); 
    } 

    //Loop ends when 8 queens have been drawn 
    while(count < 8){  

     r = rand() % 8; 
     r2 = rand() % 8; 
     sums = r + r2; 
     sums2 = r2 - r; 

     /*If space on board is empty. If row and col value have not been used. 
     Once a value of both row and col that have not been used has been reached 
     by random, mark that value between 0-7 as used.*/ 
     if((row[r] == 0) && (col[r2] == 0) && (check(sums, sum)==0)&& (check(sums2, sum2)==0)){ 

      sum[count] = sums; 
      sum2[count] = sums2; 
      row[r] = 1; 
      col[r2] = 1; 

      /*These two are used to store coordinate values in 2 arrays to be written    later.*/ 
      cRow[count] = r; 
      cCol[count] = r2; 
      count++;    
      printf("\n%d\n", r); 
      printf("%d\n", r2); 
      printf("%d\n\n", sums); 
      for(v = 0; v < 8; v++){ 
       //sum[v] = 0; 
       printf("%d", sum[v]); 
      } 
     } 
    } 

    //Print the coordinate values. 
    printf("\n"); 
    for(v = 0;v<8;v++) 
     printf("%d ", cRow[v]); 
    printf("\n"); 
    for(v = 0;v<8;v++) 
     printf("%d ", cCol[v]); 
    printf("\n"); 

    //Write the coordinate values. 
    for(i = 0; i < 8; i++){ 
     arr[cRow[i]][cCol[i]] = 'Q'; 
    } 

    //Print 2d array 
    for(i = 0; i < 8; i++){ 
     for(v = 0; v < 8; v++){ 
      printf("%c ", arr[i][v]); 
     } 
     printf("\n"); 
    } 

    return 0; 
} 

답변

2

무한 루프 문제입니다. 그 시점에서, 그것은 작동하지 않을 무의미한 선택 지점을 영원히 반복합니다. 대신, 이것에서 벗어나기 위해서는 이미 배치 한 것을 "놓지"않으면 안됩니다. 따라서 열, 행 또는 대각선에 더 이상 유효 스폿이 남아 있지 않을 때 명시 적으로 감지해야합니다.

관련 문제