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 oSample Output
Cannot win! Kim win! Kim win!
为了不wa,改了好久,才敢提交,写的代码太长了。不知道不修改那些东西,能不能ac。
思路:
幸亏平常喜欢下五子棋,各种赢的套路早就知道了,哈哈。
找出规律后判断就行了。因为只有两步,模拟一下就行了。
1 当在 . 的位置放上棋子后,如果有连续棋子大于等于2的就赢了。
2 如果在 . 的位置放上棋子后,有2个以上的连续位置大于1,那也赢了。(ps:五子棋,经常用这一招绝杀,虽然简单,百试不爽)。
3 其他都是输。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char map[5][5];
char k;
int pan(int x,int y,char q)
{
char q1;
if(q=='o')q1='x';
else q1='o';
int anslie=0,anshang=0,ans1=0,ans2=0;
for(int i=0;i<3;i++)
{
if(map[x][i]==q)anslie++;
if(map[x][i]==q1)anslie=0;
}
for(int i=0;i<3;i++)
{
if(map[i][y]==q)anshang++;
if(map[i][y]==q1)anshang=0;
}
if(x==y)
{
if(map[1][1]==q)ans1++;
else if(map[1][1]==q1)ans1--;
if(map[2][2]==q)ans1++;
else if(map[2][2]==q1)ans1--;
if(map[0][0]==q)ans1++;
else if(map[0][0]==q1)ans1--;
}
if(x+y==2)
{
if(map[0][2]==q)ans2++;
else if(map[0][2]==q1)ans2--;
if(map[1][1]==q)ans2++;
else if(map[1][1]==q1)ans2--;
if(map[2][0]==q)ans2++;
else if(map[2][0]==q1)ans2--;
}
if(anslie>=2||anshang>=2||ans1>=2||ans2>=2)
{
return 1;
}
int sum=0;
if(anslie>=1)sum++;
if(anshang>=1)sum++;
if(ans1>=1)sum++;
if(ans2>=1)sum++;
if(sum>=2)return 1;
return 0;
}
int work1(char q)
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(map[i][j]=='.')
{
if(pan(i,j,q))
{
return 1;
}
}
}
}
return 0;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
//scanf("%c",&map[i][j]);
cin>>map[i][j];
}
}
cin>>k;
/*
for(int i=0;i<3;i++)
{
printf("%s\n",map[i]);
}
*/
int tem1=work1(k);
if(tem1)
{
printf("Kim win!\n");
}
else
{
printf("Cannot win!\n");
}
}
return 0;
}