私は自分でCコースを持っています。コードを実行しても何も起こらず (何も出力されず)、問題がわかりません。そして、チェック機能が不器用であることがわかりました。どうすれば改善でき、スリムでシンプルになりますか? これが私のコードです。
#include <stdio.h>
#define ON 1
#define OFF 0
#define SIZE 8
void initial(int (*table)[SIZE]);
void setqueen(int (*table)[SIZE], const int row);
int check(const int (*table)[SIZE], const int row, const int col);
void prtable(const int (*table)[SIZE]);
int main(void)
{
int table[SIZE][SIZE];
int row = 0;
initial(table);
setqueen(table, row);
return 0;
}
void initial(int (*table)[SIZE])
{
int row, col;
for (row = 0; row < SIZE; row++)
for (col = 0; col < SIZE; col++)
table[row][col] = OFF;
}
/*
place a queen(set value = 1) in the first column of the first row and
check there is no conflict. if there is a conflict, count and move to
next column. if there is conflict in every column(count = 8), return.
if there is no conflict, call it recursively. when it place all queens,
print the table.
*/
void setqueen(int (*table)[SIZE], const int row)
{
int c = 0;
int count = 0;
for ( ; c < SIZE; c++) {
table[row][c] = ON;
if (check(table, row, c) == ON) {
table[row][c] = OFF;
count++;
continue;
}
if (count == SIZE)
return;
if (row != SIZE - 1)
setqueen(table, row + 1);
else
prtable(table);
}
}
void prtable(const int (*table)[SIZE])
{
int row, col;
for (row = 0; row < SIZE; row++) {
for (col = 0; col < SIZE; col++)
printf("%2d", table[row][col]);
putchar('\n');
}
putchar('\n');
}
int check(const int (*table)[SIZE], const int row, const int col)
{
int r = 0;
int c = 0;
for (r = 0; r < SIZE; r++)
if (r != row && table[r][col] == ON)
return ON;
for (c = 0; c < SIZE; c++)
if (c != col && table[row][c] == ON)
return ON;
for (r = row + 1, c = col + 1;
(r >= 0 && r < SIZE) || (c >= 0 && c < SIZE);
r++, c++)
if (table[r][c] == ON)
return ON;
for (r = row + 1, c = col - 1;
(r >= 0 && r < SIZE) || (c >= 0 && c < SIZE);
r++, c--)
if (table[r][c] == ON)
return ON;
for (r = row - 1, c = col + 1;
(r >= 0 && r < SIZE) || (c >= 0 && c < SIZE);
r--, c++)
if (table[r][c] == ON)
return ON;
for (r = row - 1, c = col - 1;
(r >= 0 && r < SIZE) || (c >= 0 && c < SIZE);
r--, c--)
if (table[r][c] == ON)
return ON;
return OFF;
}