Algorithm
Ilya is an experienced player in tic-tac-toe on the 4 × 4 field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by making single turn or not.
The rules of tic-tac-toe on the 4 × 4 field are as follows. Before the first turn all the field cells are empty. The two players take turns placing their signs into empty cells (the first player places Xs, the second player places Os). The player who places Xs goes first, the another one goes second. The winner is the player who first gets three of his signs in a row next to each other (horizontal, vertical or diagonal).
The tic-tac-toe position is given in four lines.
Each of these lines contains four characters. Each character is '.' (empty cell), 'x' (lowercase English letter x), or 'o' (lowercase English letter o). It is guaranteed that the position is reachable playing tic-tac-toe, and it is Ilya's turn now (in particular, it means that the game is not finished). It is possible that all the cells are empty, it means that the friends left without making single turn.
Print single line: "YES" in case Ilya could have won by making single turn, and "NO" otherwise.
xx..
.oo.
x...
oox.
YES
x.ox
ox..
x.o.
oo.x
NO
x..x
..oo
o...
x.xo
YES
o.x.
o...
.x..
ooxx
NO
In the first example Ilya had two winning moves: to the empty cell in the left column and to the leftmost empty cell in the first row.
In the second example it wasn't possible to win by making single turn.
In the third example Ilya could have won by placing X in the last row between two existing Xs.
In the fourth example it wasn't possible to win by making single turn.
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <bits/stdc++.h>
using namespace std;
char g[6][7];
bool can() {
for(int i = 1; i < 5; ++i)
for(int j = 1; j < 5; ++j) {
if(g[i][j] == 'x') {
if(g[i - 1][j] == 'x' && g[i + 1][j] == 'x')
return true;
if(g[i][j - 1] == 'x' && g[i][j + 1] == 'x')
return true;
if(g[i - 1][j - 1] == 'x' && g[i + 1][j + 1] == 'x')
return true;
if(g[i - 1][j + 1] == 'x' && g[i + 1][j - 1] == 'x')
return true;
}
}
return false;
}
int main() {
for(int i = 1; i < 5; ++i)
scanf("%s", g[i] + 1);
for(int i = 1; i < 5; ++i)
for(int j = 1; j < 5; ++j) {
if(g[i][j] == '.') {
g[i][j] = 'x';
if(can()) {
puts("YES");
return 0;
}
g[i][j] = '.';
}
}
puts("NO");
return 0;
}
Copy The Code &
Try With Live Editor
Input
.oo.
x...
oox.
Output
Demonstration
Codeforces Solution-Ilya and tic-tac-toe game-Solution in C, C++, Java, Python