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.
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.
For each test case:
If Kim can win in 2 steps, output “Kim win!”
Otherwise output “Cannot win!”
3 . . . . . . . . . o o x o o . x x x o x o x . . o . . . x o
Cannot win!
Kim win!
Kim win!
思维很重要! 做这个题的时候,我当时没有想出好方法,看了一下别人的思路,大概是这样的,首先我们暴力枚举一个位子,使得这个位子
就是Kim下的位子,然后检查一下能否成功,然而我们不枚举对方怎么走,因为对方足够聪明,然而我们要想下一步走到哪里
会赢,如果有这么一个位子对方肯定要阻止,Kim下一步,如果有两个或者两个以上的位子可以放置,那么这样就赢了。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int a[5][5];
int check(int x)
{
if(a[0][0]==a[0][1]&&a[0][1]==a[0][2]&&a[0][0]==x)
return 1;
if(a[1][0]==a[1][1]&&a[1][1]==a[1][2]&&a[1][0]==x)
return 1;
if(a[2][0]==a[2][1]&&a[2][1]==a[2][2]&&a[2][0]==x)
return 1;
if(a[0][0]==a[1][1]&&a[1][1]==a[2][2]&&a[0][0]==x)
return 1;
if(a[0][2]==a[1][1]&&a[1][1]==a[2][0]&&a[0][2]==x)
return 1;
if(a[0][0]==a[1][0]&&a[1][0]==a[2][0]&&a[0][0]==x)
return 1;
if(a[0][1]==a[1][1]&&a[1][1]==a[2][1]&&a[0][1]==x)
return 1;
if(a[0][2]==a[1][2]&&a[1][2]==a[2][2]&&a[0][2]==x)
return 1;
return 0;
}
int fun(int x)
{
int ans=0;
if(check(x)==1)
return 1;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
if(a[i][j]==0)
{
a[i][j]=x;
if(check(x)==1)
ans++;
a[i][j]=0;
}
}
if(ans>=2)
return 1;
else
return 0;
}
int main()
{
int T;
char s1[5],s2[5];
scanf("%d",&T);
while(T--)
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
scanf("%s",s1);
if(s1[0]=='.')
a[i][j]=0;
if(s1[0]=='x')
a[i][j]=1;
if(s1[0]=='o')
a[i][j]=2;
}
int x,flag=0;
scanf("%s",s2);
if(s2[0]=='.')
x=0;
if(s2[0]=='x')
x=1;
if(s2[0]=='o')
x=2;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
if(a[i][j]==0)
{
a[i][j]=x;
if(fun(x)==1)
flag=1;
a[i][j]=0;
}
}
if(flag)
printf("Kim win!\n");
else
printf("Cannot win!\n");
}
return 0;
}