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!
題意就是在走兩步能不能贏 自己模擬不出來 比着隊友的寫的QAQ
#include <iostream>
#include<cstdio>
#include<stack>
#include<cstring>
#include<algorithm>
using namespace std;
char maps[5][5];
int check(char a)
{
if(maps[0][0]==maps[0][1]&&maps[0][2]==maps[0][0]&&maps[0][0]==a)
return 1;
else if(maps[0][0]==maps[1][1]&&maps[2][2]==maps[0][0]&&maps[0][0]==a)
return 1;
else if(maps[1][0]==maps[2][0]&&maps[0][0]==maps[1][0]&&maps[1][0]==a)
return 1;
else if(maps[1][0]==maps[1][1]&&maps[1][2]==maps[1][0]&&maps[1][0]==a)
return 1;
else if(maps[2][0]==maps[2][1]&&maps[2][0]==maps[2][2]&&maps[2][0]==a)
return 1;
else if(maps[0][1]==maps[1][1]&&maps[2][1]==maps[0][1]&&maps[0][1]==a)
return 1;
else if(maps[0][2]==maps[1][2]&&maps[2][2]==maps[0][2]&&maps[0][2]==a)
return 1;
else if(maps[0][2]==maps[1][1]&&maps[2][0]==maps[0][2]&&maps[0][2]==a)
return 1;
else
return 0;
}
int main()
{
int t;
cin>>t;
while(t--)
{
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
cin>>maps[i][j];
}
char a;
cin>>a;
int count=0,flag1=0,flag2=0;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(maps[i][j]=='.') //下第一步 這時隊手沒下 所以如果可以練成一條線就贏了
{
maps[i][j]=a; //和開場贏一起考慮在內了
if(check(a))
{
flag1=1;
break;
}
count=0; //用於數有幾種贏法
for(int k=0;k<3;k++)
{
for(int l=0;l<3;l++)
{
if(maps[k][l]=='.')
{
maps[k][l]=a;
if(check(a))
{
count++;
}
if(count>1) //贏法有兩種就能贏
{
flag2=1;
break;
}
maps[k][l]='.'; // 回溯
}
}
if(flag2)break;
}
maps[i][j]='.'; //第一步回溯
}
}
if(flag1||flag2)break;
}
if(flag1||flag2)
cout<<"Kim win!"<<endl;
else
cout<<"Cannot win!"<<endl;
}
return 0;
}