-
Notifications
You must be signed in to change notification settings - Fork 0
/
tic_tac_toe.cpp
101 lines (93 loc) · 2.37 KB
/
tic_tac_toe.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
* =====================================================================================
*
* Filename: tic_tac_toe.cpp
*
* Description: 348. Design Tic-Tac-Toe.
* https://leetcode.com/problems/design-tic-tac-toe/
*
* Version: 1.0
* Created: 03/02/2024 16:51:20
* Revision: none
* Compiler: gcc
*
* Author: [email protected]
* Organization:
*
* =====================================================================================
*/
#include <tuple>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using std::tuple;
using std::vector;
class TicTacToe {
public:
TicTacToe(int n) : matrix_(n, vector<int>(n)) {}
int move(int row, int col, int player) {
const int n = matrix_.size();
matrix_[row][col] = player;
for (int i = 0; i < n; i++) {
if (matrix_[row][i] != player) {
break;
}
if (i == n - 1) {
return player;
}
}
for (int i = 0; i < n; i++) {
if (matrix_[i][col] != player) {
break;
}
if (i == n - 1) {
return player;
}
}
if (row == col) {
for (int i = 0; i < n; i++) {
if (matrix_[i][i] != player) {
break;
}
if (i == n - 1) {
return player;
}
}
}
if (row + col == n - 1) {
for (int i = 0; i < n; i++) {
if (matrix_[i][n - i - 1] != player) {
break;
}
if (i == n - 1) {
return player;
}
}
}
return 0;
}
private:
vector<vector<int>> matrix_;
};
TEST(Solution, move2) {
TicTacToe tic_tac_toe(2);
vector<tuple<int, int, int, int>> moves = {
std::make_tuple(0, 1, 1, 0),
std::make_tuple(1, 1, 2, 0),
std::make_tuple(1, 0, 1, 1),
};
for (auto& c : moves) {
EXPECT_EQ(tic_tac_toe.move(std::get<0>(c), std::get<1>(c), std::get<2>(c)), std::get<3>(c));
}
}
TEST(Solution, move3) {
TicTacToe tic_tac_toe(3);
vector<tuple<int, int, int, int>> moves = {
std::make_tuple(0, 0, 1, 0), std::make_tuple(0, 2, 2, 0), std::make_tuple(2, 2, 1, 0),
std::make_tuple(1, 1, 2, 0), std::make_tuple(2, 0, 1, 0), std::make_tuple(1, 0, 2, 0),
std::make_tuple(2, 1, 1, 1),
};
for (auto& c : moves) {
EXPECT_EQ(tic_tac_toe.move(std::get<0>(c), std::get<1>(c), std::get<2>(c)), std::get<3>(c));
}
}