ปานกลาง 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.

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก