2012-07-25 43 views
0

執行此代碼時,我的終端掛起大部分時間,但每過一段時間我都會得到我想要打印的解決方案。我知道這不是解決女王難題的最佳方式,所以請不要評論。感謝任何花時間幫助的人。8皇后拼圖:使用隨機數導致無限循環

#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

無限循環的問題是因爲你的程序不能「走回頭路」,如果它曾經到達一個點,它是不可能從法律上放置更多的皇后。那時,它會永遠循環地永遠徒勞無益地選擇不起作用的點。相反,要擺脫這種情況,它需要「擺脫」它已經放置的東西。 (因此,您將需要明確檢測何時在列,行或對角線上沒有更多合法點。)