foj Problem 2283 Tic-Tac-Toe
Accept: 60 Submit: 92
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
Sample Output
#define _CRT_SECURE_NO_DEPRECATE #include<iostream> #include<algorithm> #include<queue> #include<set> #include<vector> #include<cstring> #include<string> #include<bitset> using namespace std; #define INF 0x3f3f3f3f const int N_MAX = 3; char field[N_MAX][N_MAX]; char p; bool judge() { bool flag = 1; if (field[0][0] == p && field[1][1] == p && field[2][2] == p)return true; if (field[2][0] == p && field[1][1] == p && field[0][2] == p)return true; for (int i = 0; i < N_MAX;i++) { for (int j = 0; j < N_MAX;j++) { if (field[i][j] != p) { flag = 0; break; } } if (flag)return true; else flag = 1; } for (int i = 0; i < N_MAX; i++) { for (int j = 0; j < N_MAX; j++) { if (field[j][i] != p) { flag = 0; break; } } if (flag)return true; else flag = 1; } return false; } int main() { int t; scanf("%d",&t); while(t--){ bool flag1 = 0,flag2=0; for (int i = 0; i < N_MAX;i++) { for (int j = 0; j < N_MAX;j++) { scanf(" %c",&field[i][j]); } } scanf(" %c",&p); for (int i = 0; i < N_MAX; i++) { for (int j = 0; j < N_MAX;j++) { if(field[i][j]=='.'){ field[i][j] = p; if (judge()) { flag1 = 1; break; }//直接下一步就搞定了 int num = 0; for (int k = 0; k < N_MAX;k++) {//否则下两步,看看能否赢 for (int l = 0; l < N_MAX;l++) { if (field[k][l] == '.') { field[k][l] = p; if (judge())num++;//找到一种可行的赢法,赢的可能数加1 if (num >= 2) { flag2 = 1; break; } field[k][l] = '.'; } } if (flag2)break; } field[i][j] = '.'; if (flag2)break; } } if (flag1||flag2)break; } if (flag1 || flag2)printf("Kim win!\n"); else printf("Cannot win!\n"); } return 0; }