보통 0명 해결 정답률 0%

Minimax Tic-Tac-Toe

Pick the perfect tic-tac-toe move by searching the whole game tree with minimax.

배우게 될 내용

  • Search every possible future move
  • Score positions from the current player's view
  • Pick the optimal move recursively

문제

번역본 보기

Minimax is how game-playing programs choose moves: assume both players play perfectly, score every finished game, and back the scores up the game tree. The player to move picks the child with the highest score for itself.

The board is a 9-character string read row by row (indices 0-8), with "X", "O" or "." for an empty cell. X always moves first, so it is X's turn when both have the same number of marks and O's turn otherwise.

Score a finished game from the point of view of the player to move: +1 for a win, 0 for a draw, -1 for a loss. Return the empty cell whose move has the best minimax score; if several are equally good, return the lowest index.

Implement best_move(board).

Input

board: A valid position where nobody has won yet and at least one cell is empty.

Output

Return the index (0-8) of the best move.

제약 조건

board has exactly 9 characters, each X, O or .

The position is reachable in a real game, nobody has won, and at least one cell is empty

예시

예시 1
입력:
board = "XX.OO...."

예상 출력:
expected = 2
입력:
std::string board = "XX.OO....";

예상 출력:
long long expected = 2;
입력:
string board = "XX.OO....";

예상 출력:
long expected = 2;

설명

X and O have two marks each, so X moves. Playing 2 completes the top row and wins at once (+1).

예시 2
입력:
board = "X..OO...X"

예상 출력:
expected = 5
입력:
std::string board = "X..OO...X";

예상 출력:
long long expected = 5;
입력:
string board = "X..OO...X";

예상 출력:
long expected = 5;

설명

X moves. O threatens to complete the middle row at 5. Every other move lets O win (-1), while blocking at 5 leads to a draw (0), so the answer is 5.

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

Determine whose turn it is from the counts of X and O, then evaluate every legal move recursively.

힌트 2

Score terminal boards from the current player’s perspective, and choose the move that maximizes that value.

힌트 3

If multiple moves tie, keep the earliest empty cell index, and ensure wins are detected before considering further moves.

예상 복잡도

O(9!) time, O(9) extra space

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.