|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
喜欢小甲鱼讲课的风格,讲八皇后问题的时候我觉得那点数组指针太饶人了。自己稍微修改了一点,分享给大家。
#include <stdio.h>
#include <stdlib.h>
//参数row表士行
//参数n表示列
//参数(*chess)[8]表示指向期盼每一行的指针
int count = 0;
int notdanger(int row, int j, int chess[8][8])
{
int i,k ,flag1 = 0, flag2 = 0, flag3 = 0, flag4 = 0, flag5 = 0;
//判断列
for ( i = 0; i < 8; i++)
{
//*(*chess + i) + j
if (chess[i][j]!=0)
{
flag1 = 1;
break;
}
}
//判断左上方
for ( i = row, k=j; i >=0&&k>=0; i--,k--)
{
if (chess[i][k]!=0)
{
flag2 = 1;
break;
}
}
//判断右下方
for ( i = row, k = j; i<8 && k<8; i++, k++)
{
if (chess[i][k] != 0)
{
flag3 = 1;
break;
}
}
//判断右上方
for ( i = row, k = j; i >=0 && k<8; i--, k++)
{
if (chess[i][k] != 0)
{
flag4 = 1;
break;
}
}
//判断左下方
for ( i = row, k = j; i <8 && k>=0; i++, k--)
{
if (chess[i][k] != 0)
{
flag5 = 1;
break;
}
}
if (flag1 || flag2 || flag3 || flag4||flag5)
{
return 0;
}
else
{
return 1;
}
}
void eightqueen(int row,int n,int chess[8][8])
{
int chess2[8][8],i,j;
for ( i = 0; i < 8; i++)
{
for ( j = 0; j < 8; j++)
{
chess2[i][j] = chess[i][j];
}
}
if (row==8)
{
printf("第 %d 种\n", count+1);
for ( i = 0; i < 8; i++)
{
for ( j = 0; j < 8; j++)
{
printf("%d ", chess2[i][j]);//等下试一下chess2[i][j]
}
printf("\n");
}
printf("\n");
count++;
}
else
{
for ( j = 0; j < n; j++)
{
if (notdanger(row, j, chess) != 0)//判断是否危险
{
for ( i = 0; i < 8; i++)
{
chess2[row][i] = 0;
//*(*(chess2 + row) + i) = 0;//把这一行所有的列都赋值为0
}
chess2[row][j] = 1;
//*(*(chess2 + row) + j) = 1;//把这行这列赋值为1
eightqueen(row + 1, n, chess2);
}
}
}
}
void main()
{
int chess[8][8];
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
chess[i][j] = 0;
}
}
eightqueen(0,8,chess);
printf("%d 一共有",count);
} |
|