您的位置:首页 > 其它

FZU2283-Tic-Tac-Toe

2017-08-21 20:07 162 查看

Tic-Tac-Toe

Kim likes to play Tic-Tac-Toe.

Given a current state, and now Kim is going to take his next move. Please tell Kim if he can win the game in next 2 moves if both player are clever enough.

Here “next 2 moves” means Kim’s 2 move. (Kim move,opponent move, Kim move, stop).



Game rules:

Tic-tac-toe (also known as noughts and crosses or Xs and Os) is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row wins the game.

Input

First line contains an integer T (1 ≤ T ≤ 10), represents there are T test cases.

For each test case: Each test case contains three lines, each line three string(“o” or “x” or “.”)(All lower case letters.)

x means here is a x

o means here is a o

. means here is a blank place.

Next line a string (“o” or “x”) means Kim is (“o” or “x”) and he is going to take his next move.

Output

For each test case:

If Kim can win in 2 steps, output “Kim win!”

Otherwise output “Cannot win!”

Sample Input

3







o

o x o

o . x

x x o

x

o x .

. o .

. . x

o

Sample Output

Cannot win!

Kim win!

Kim win!

题目大意:三子棋,kim先下,问三步之内能否获胜。

解题思路: dfs搜索,参考了斌神的代码,简洁清晰~

dfs(er,step)代表现在er下,若赢返回er,若平局返回0,否则返回3−er(另一个人)赢,注意三者的先后关系。

#include<iostream>
#include<cstdio>
#include<cmath>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
const int MAXN=1e5+5;
int mat[5][5];

int check()
{
for(int i=1;i<=3;i++)
if(mat[i][1]&&mat[i][1]==mat[i][2]&&mat[i][2]==mat[i][3]) return mat[i][1];
for(int j=1;j<=3;j++)
if(mat[1][j]&&mat[1][j]==mat[2][j]&&mat[2][j]==mat[3][j]) return mat[1][j];
if(mat[1][1]&&mat[1][1]==mat[2][2]&&mat[2][2]==mat[3][3]) return mat[1][1];
if(mat[1][3]&&mat[1][3]==mat[2][2]&&mat[2][2]==mat[3][1]) return mat[1][3];
return 0;
}

int dfs(int er,int step)
{
int tmp=check();if(tmp!=0) return tmp;
if(step==4) return 0;
bool tie=false;
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
if(mat[i][j]==0)
{
mat[i][j]=er;
int ans=dfs(3-er,step+1);
mat[i][j]=0;
if(ans==er) return er;
if(ans==0)  tie=true;
}
}
}
if(tie) return 0;
return 3-er;
}

int main()
{
int T;
scanf("%d",&T);
while(T--)
{
char ch[3];
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
scanf("%s",&ch);
if(ch[0]=='.') mat[i][j]=0;
else if(ch[0]=='o') mat[i][j]=1;
else mat[i][j]=2;
}
}
char op[3];
scanf("%s",op);
int er;
if(op[0]=='o') er=1; else er=2;
if(dfs(er,1)==er) printf("Kim win!\n");
else printf("Cannot win!\n");
}
return 0;
}
/*
3
. . .
. . .
. . .
o
o x o
o . x
x x o
x
o x .
. o .
. . x
o
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: