八皇后问题
萌新第一次发博客,格式方面会有很多问题,大家多多包涵。
在网上看的答案,很简单,我一度怀疑我是不是写错了。新手练习不免程序不够精炼,也存在一些问题。整个八皇后问题程序跑出108个解,里面有些是重复,但我实在不知道怎么排除重复解,只能这样了。
#include<stdio.h>
#define False 0
#define True 1
/*
输出了所有八皇后问题解,但没有排除相同解*/
int total_count = 0;
int min(int a, int b)
{
if(a <= b)
return a;
else
return b;
}
void print(int array[][8])
{
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
printf("%d ", array[i][j]);
}
printf("\n");
}
}
//攻击检查
int check_attack(int row, int col, int checkboard[][8])
{
int min_number = min(row, col);
int left_row = row - min_number;
int left_col = col - min_number;
int sum = 0;
for(int i = 0; i < 8; i++)
{
if(checkboard[row][i] == 1 && i != col)
return False;
} //检查一行(排除选中的位置)
for(int i = 0; i < 8; i++)
{
if(checkboard[i][col] == 1 && i != row)
return False;
} //检查一列(排除选中的位置)
for(int i = 0; left_row < 8 && left_col < 8; i++)
{
if(checkboard[left_row][left_col] == 1 && left_row != row)
return False;
left_row++;
left_col++;
} //检查一撇(排除选中的位置)
for(int r = row, c = col; r < 8 && c < 8 && r >=0 && c >= 0; r--, c++)
{
if(checkboard[r][c] == 1 && r != row)
return False;
}
for(int r = row, c = col; r < 8 && c < 8 && r >=0 && c >= 0; r++, c--)
{
if(checkboard[r][c] == 1 && r != row)
return False;
}
return True;
}
int set_queen(int row, int checkboard[][8],int count)
{
if(count < 8) /*一共循环8次,若循环了八次
代表八皇后问题已经得出解*/
{
for(int col = 0; col < 8; col++)
{
for(int i = 0; i < 8; i++)
checkboard[row][i] = 0; /*在进行攻击检查前将本行全部置零
防止递归返回时,有一个位置已经置一了*/
int flag = check_attack(row, col, checkboard); //选中检查攻击
if(flag)
{
checkboard[row][col] = 1;
set_queen((row+1)%8, checkboard, count+1);
}
}
}
else
{
print(checkboard);
printf("----------------------------\n");
total_count++;
}
}
int main()
{
int count;
for(int rt = 0; rt < 8; rt++)
{
int array[8][8] = {
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0}
};
set_queen(rt, array, 0);
printf("----------------------------------------------%d\n", total_count + 1);
}
printf("%d", total_count);
}