要点:将 对角线、列用数组进行标记,加快搜索速度
#include<iostream>
#include<stdio.h>
using namespace std;
int Max = 0;
int m[9][9];
bool A[20] = {false};//右上左下
bool B[20] = {false};//左上右下
bool C[20] = {false};//列
void dfs(int deep,int S){
if(deep==8){
if(S>Max){
Max = S;
}
return;
}
for(int i=1;i<=8;i++){
if(A[i+deep]==false&&B[i+8-deep-1]==false&&C[i]==false){
A[i+deep] = true;
B[i+8-deep-1] = true;
C[i] = true;
dfs(deep+1,S+m[deep+1][i]);
A[i+deep] = false;
B[i+8-deep-1] = false;
C[i] = false;
}
}
}
int main(){
//freopen("in.txt","r",stdin);
for(int i=1;i<=8;i++){
for(int j=1;j<=8;j++){
cin>>m[i][j];
}
}
dfs(0,0);
cout<<Max<<'\n';
return 0;
}