-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMin - Max.cpp
97 lines (94 loc) · 2.96 KB
/
Min - Max.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
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
int evaluate(const vector<vector<char>>& board) {
for (int row = 0; row < 3; row++) {
if (board[row][0] == board[row][1] && board[row][1] == board[row][2]) {
if (board[row][0] == 'X') return 10;
if (board[row][0] == 'O') return -10;
}
}
for (int col = 0; col < 3; col++) {
if (board[0][col] == board[1][col] && board[1][col] == board[2][col]) {
if (board[0][col] == 'X') return 10;
if (board[0][col] == 'O') return -10;
}
}
if (board[0][0] == board[1][1] && board[1][1] == board[2][2]) {
if (board[0][0] == 'X') return 10;
if (board[0][0] == 'O') return -10;
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0]) {
if (board[0][2] == 'X') return 10;
if (board[0][2] == 'O') return -10;
}
return 0;
}
bool isMovesLeft(const vector<vector<char>>& board) {
for (const auto& row : board) {
for (char cell : row) {
if (cell == '_') return true;
}
}
return false;
}
int minimax(vector<vector<char>>& board, int depth, bool isMaximizingPlayer) {
int score = evaluate(board);
if (score == 10 || score == -10) return score;
if (!isMovesLeft(board)) return 0;
if (isMaximizingPlayer) {
int best = INT_MIN;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == '_') {
board[i][j] = 'X';
best = max(best, minimax(board, depth + 1, false));
board[i][j] = '_';
}
}
}
return best;
}
else {
int best = INT_MAX;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == '_') {
board[i][j] = 'O';
best = min(best, minimax(board, depth + 1, true));
board[i][j] = '_';
}
}
}
return best;
}
}
pair<int, int> findBestMove(vector<vector<char>>& board) {
int bestValue = INT_MIN;
pair<int, int> bestMove = {-1, -1};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == '_') {
board[i][j] = 'X'; // Assume 'X' is the maximizing player
int moveValue = minimax(board, 0, false);
board[i][j] = '_';
if (moveValue > bestValue) {
bestMove = {i, j};
bestValue = moveValue;
}
}
}
}
return bestMove;
}
int main() {
vector<vector<char>> board = {
{'X', 'O', 'X'},
{'O', 'O', '_'},
{'_', '_', '_'}
};
pair<int, int> bestMove = findBestMove(board);
cout << "The best move is: Row = " << bestMove.first << ", Col = " << bestMove.second << endl;
return 0;
}