问题描述
规则同8皇后问题,但是棋盘上每格都有一个数字,要求八皇后所在格子数字之和最大。
输入格式
一个8*8的棋盘。
输出格式
所能得到的最大数字和
样例输入
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
48 50 51 52 53 54 55 56
57 58 59 60 61 62 63 64
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
48 50 51 52 53 54 55 56
57 58 59 60 61 62 63 64
样例输出
260
数据规模和约定
棋盘上的数字范围0~99
#include<stdio.h>
int max=0;
//int count=0;
int arr[8][8];
int notDangerous(int line,int row,int temp[][8])
{
int flag1=1,flag2=1,flag3=1,flag4=1,flag5=1;
int i,j;
for(j=0;j<=7;j++) //竖线
{
if(temp[j][row]==1)
{
flag1=0;
break;
}
}
for(i=line,j=row;i>=0 && j>=0;i--,j--) //左上方 for(;;)里面判断条件的时候要用&&,不能用逗号
{
if(temp[i][j]==1)
{
flag2=0;
break;
}
}
for(i=line,j=row;i>=0 && j<=7;i--,j++) //右上方
{
if(temp[i][j]==1)
{
flag3=0;
break;
}
}
for(i=line,j=row;i<=7 && j>=0;i++,j--) //左下方
{
if(temp[i][j]==1)
{
flag4=0;
break;
}
}
for(i=line,j=row;i<=7 && j<=7;i++,j++) //右下方
{
if(temp[i][j]==1)
{
flag5=0;
break;
}
}
if(flag1==0 || flag2==0 || flag3==0 || flag4==0 || flag5==0)
{
return 0;
}
else
{
return 1;
}
}
void eightQueen(int start,int end,int Qipan[][8])
{
int temp[8][8];
int sum=0,i,j;
for(i=0;i<=end;i++)
{
for(j=0;j<=end;j++)
{
temp[i][j]=Qipan[i][j];
}
}
if(start>end)
{
// count++;
for(i=0;i<=end;i++)
{
for(j=0;j<=end;j++)
{
if(temp[i][j]==1)
{
sum+=arr[i][j];
}
}
}
if(sum>max)
{
max=sum;
}
}
else
{
for(i=0;i<=end;i++)
{
if(notDangerous(start,i,temp)==1)
{
for(j=0;j<=end;j++)
{
temp[start][j]=0;
}
temp[start][i]=1;
eightQueen(start+1,end,temp);
}
}
}
}
int main()
{
int i,j;
int Qipan[8][8]={0};
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
scanf("%d",&arr[i][j]);
}
}
eightQueen(0,7,Qipan);
// printf("%d\n",count);
printf("%d\n",max);
return 0;
}