A game of tic-tac-toe is played on a 3 × 3 square grid. Each cell is either empty (denoted by '.') or occupied by one of the two players ('X' and 'O'). X goes first and then they take turns alternatively. If X is written three times in a straight line, then X wins and the game ends. The same goes for O. If there is no empty cell left, then the game ends as a draw.
You are given the description of a game of tic-tac-toe. You have to determine the state of the game.
The states of the game are as follows:
- If the game is invalid, that is, if there is no possibility of it happening, output "Wait, what?".
- If X has won, then print "X won." else if O has won print "O won.".
- If it is a draw, then print "It is a draw.".
- Otherwise, print whose turn it is, "X's turn." or "O's turn." accordingly.
Example:
Input: arr = {"O.X", ".OX", "..X"}
Output: X won.
Approach
C++
#include <bits/stdc++.h>using namespace std;char ticTacToe(map<int, char> &s){char winner = '.';if (s[1] == s[2] && s[1] == s[3] && s[1] != '.'){winner = s[1];}if (s[4] == s[5] && s[4] == s[6] && s[4] != '.'){if (winner == '.' || s[4] == winner){winner = s[4];}elsereturn 'E';}if (s[7] == s[8] && s[7] == s[9] && s[7] != '.'){if (winner == '.' || s[7] == winner){winner = s[7];}elsereturn 'E';}if (s[1] == s[4] && s[1] == s[7] && s[1] != '.'){if (winner == '.' || s[1] == winner){winner = s[1];}elsereturn 'E';}if (s[2] == s[5] && s[2] == s[8] && s[2] != '.'){if (winner == '.' || s[2] == winner){winner = s[2];}elsereturn 'E';}if (s[3] == s[6] && s[3] == s[9] && s[3] != '.'){if (winner == '.' || s[3] == winner){winner = s[3];}elsereturn 'E';}if (s[1] == s[5] && s[1] == s[9] && s[1] != '.'){if (winner == '.' || s[1] == winner){winner = s[1];}elsereturn 'E';}if (s[3] == s[5] && s[3] == s[7] && s[3] != '.'){if (winner == '.' || s[3] == winner){winner = s[3];}elsereturn 'E';}return winner;}int main(){bool possible = true;map<int, char> spaces;int x = 0;int o = 0;vector<string> arr = {"O.X", ".OX", "..X"};for (int i = 0; i <= 2; i++){string input = arr[i];if (input.size() != 3){possible = false;break;}for (int j = 1; j <= 3; j++){if (input[j - 1] == 'X'){spaces[i * 3 + j] = 'X';x++;}else if (input[j - 1] == 'O'){spaces[i * 3 + j] = 'O';o++;}else if (input[j - 1] == '.'){spaces[i * 3 + j] = '.';}else{cout << input[j] << "\n";possible = false;break;}}}if (!possible)cout << "Wait, what?";else if (o + 1 < x)cout << "Wait, what?";else if (o > x)cout << "Wait, what?";else{char winner = ticTacToe(spaces);if (winner == 'E')cout << "Wait, what?";else if (winner == 'X'){if (x == o)cout << "Wait, what?";elsecout << "X won.";}else if (winner == 'O'){if (x != o)cout << "Wait, what?";elsecout << "O won.";}else if (x + o == 9)cout << "It's a draw.";else if (x == o)cout << "X's turn.";elsecout << "O's turn.";}return 0;}
No comments:
Post a Comment