8个皇后谜题:使用随机数导致无限循环

时间:2012-07-25 05:30:12

标签: c random infinite-loop n-queens

执行此代码时,我的终端大部分时间都会挂起,但每隔一段时间我就会得到我想要打印出来的解决方案。我知道这不是解决女王拼图的最佳方法,所以请不要对此发表评论。感谢任何需要时间帮助的人。

#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;
}

1 个答案:

答案 0 :(得分:2)

无限循环问题是因为如果程序无法合法地放置任何更多的皇后,你的程序就无法“回溯”。在这一点上,它只是徒劳地循环挑选无效的斑点。相反,为了突破这一点,它需要“取消”已经放置的东西。 (因此,您需要明确检测何时列,行或对角线中没有剩余合法位置。)