Problem 2283 Tic-Tac-Toe
Accept: 159 Submit: 340
Time Limit: 1000 mSec Memory Limit : 262144 KB
Problem Description
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!
Source
第八届福建省大学生程序设计竞赛-重现赛(感谢承办方厦门理工学院)
题意 : 给出一个 3 * 3 的 棋局,以及先手的棋子 o ,轮到先手下,有三枚棋子连着者获胜,问先手下次,对方下一次,先手再下一次,先手能否获胜
思路 : 先手已经有两枚棋子连着了且第三个点没有对方的落子,是否存在一个 ‘.’,先手在该位置落子后可以形成至少在两条线上有两枚自己的落子(算上刚刚下),以上情况可获胜,其余不能获胜(给出的棋局似乎没有已经有三枚相同的棋子相连的情况,似乎也没有对方 已有两枚举连着的棋子,先手下一次必须去堵一下情况)
AC代码:
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX = 1e5 + 10;
typedef long long LL;
char s[4][4],c[2],ss[2];
int ok,fx[20]= {-1,1,-1,1,0,0,1,2,0,0,1,2,-1,-2,0,0,-1,-2},fy[20] = {-1,1,0,0,-1,1,1,2,1,2,0,0,-1,-2,-1,-2,0,0};
void dfs(int x,int y,char o,int sum){
int p = 0;
for(int i = 0; i < 18; i += 2){
int ans = 0,xx = x + fx[i],yy = y + fy[i],x2 = x + fx[i + 1],y2 = y + fy[i + 1];
if(xx >= 0 && yy >= 0 && xx < 3 && yy < 3 && x2 >= 0 && y2 >= 0 && x2 < 3 && y2 < 3){
if(s[xx][yy] != o && s[xx][yy] != '.') continue;
if(s[x2][y2] != o && s[x2][y2] != '.') continue;
if(s[xx][yy] == o) ans++;
if(s[x2][y2] == o) ans++;
if(ans) p++;
if(ans + sum == 2 || p == 2){ ok = 1; return ;}
}
}
}
int main()
{
int T; scanf("%d",&T);
while(T--){
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3 ;j++)
scanf("%s",ss),s[i][j] = ss[0];
scanf("%s",c);
ok = 0;
for(int i = 0; i < 3 && !ok; i++)
for(int j = 0; j < 3 && !ok; j++)
if(s[i][j] == c[0] || s[i][j] == '.')
if(s[i][j] == c[0]) dfs(i,j,c[0],1);
else dfs(i,j,c[0],0);
if(ok) puts("Kim win!");
else puts("Cannot win!");
}
return 0;
}