このコードを実行すると、ほとんどの場合、端末がハングしますが、ときどき、必要なソリューションが出力されます。これが女王のパズルを解く最良の方法ではないことはわかっているので、コメントしないでください. 時間を割いて助けてくれた人に感謝します。
#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;
}