考察:
本题主要考察了极大极小+dfs的使用,之前在学校学的都没有遍历到叶子节点。
思路:
这题只告诉了叶子结点的情况,因此需要用dfs+后序遍历的思想去求当前节点的max,min
相关代码如下:
//极大极小+深度优先
#include <iostream>
#include <algorithm>
using namespace std;
int mat[9]; //matrix
const int ttl=9; //total number
int T; //number of examples
int check(int a[]){ //判断是否为叶节点
bool isA=0;
int which;
for(int i=0;!isA&&i<3;i++){
if(a[i]==a[i+3]&&a[i+3]==a[i+6]){
isA=1; which=a[i]; break;
}
}
for(int i=0;!isA&&i<9;i+=3){
if(a[i]==a[i+1]&&a[i+1]==a[i+2]){
isA=1; which=a[i]; break;
}
}
if(!isA&&a[0]==a[4]&&a[4]==a[8]){
isA=1; which=a[0];
}
if(!isA&&a[2]==a[4]&&a[4]==a[6]){
isA=1; which=a[2];
}
int cnt=0;
for(int i=0;i<9;i++){
if(!a[i]) cnt++;
}
if(isA&&which==1) return cnt+1;
if(isA&&which==2) return -cnt-1;
if(cnt==0) return 0;
return -100;
}
int dfs(int a[],int who){
int chk=check(a);
if(chk!=-100) return chk;
int tmpMax=-100,tmpMin=100;
for(int i=0;i<ttl;i++){ //依次进行dfs遍历即进入下一层
if(!a[i]&&who==1){
a[i]=1;
tmpMax=max(tmpMax,dfs(a,2));
}
else if(!a[i]&&who==2){
a[i]=2;
tmpMin=min(tmpMin,dfs(a,1));
}
a[i]=0;
}
return who==1?tmpMax:tmpMin;
}
int main(){
//cin
int value;
cin>>T;
for(int i=0;i<T;i++){
for(int j=0;j<ttl;j++){
cin>>mat[j];
}
value=dfs(mat,1);
cout<<value<<endl;
}
return 0;
}
很不幸,75分,未能完全通过,如果有兴趣的朋友帮我找下问题吧
参考了http://bubuko.com/infodetail-2754332.html 的思路
仅供参考