2018-3 棋局(C++)

考察:

       本题主要考察了极大极小+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 的思路

仅供参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值