0

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

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

1 回答 1

2

无限循环问题是因为如果您的程序到达无法合法放置更多皇后的地步,它就无法“回溯”。那时,它只会永远循环,徒劳地挑选不起作用的地方。相反,要摆脱这种情况,它需要“取消放置”它已经放置的东西。(因此,您将需要明确检测列、行或对角线中何时不再有合法点。)

于 2012-07-25T05:39:19.887 回答