Trung bình 3 người đã giải Tỷ lệ chấp nhận 60.0%

Tic-Tac-Toe Winner

Decide the result of a tic-tac-toe board.

Bạn sẽ học được gì

  • Check rows, columns and diagonals
  • Detect a draw or an unfinished game
  • Keep grid checks readable

Đề bài

Xem bản dịch

A 3×3 board is given as three strings of X, O and . (empty). A player wins with three of their marks in a row, column or diagonal. Boards never have two winners.

Implement tic_tac_toe_winner(board).

Input

board: Three rows of three characters each.

Output

Return "X" or "O" for the winner, "Draw" if the board is full with no winner, or "Pending" if empty cells remain and nobody has won.

Ràng buộc

board has exactly 3 rows of length 3

Ví dụ

Ví dụ 1
Đầu vào:
board = ["XOX", ".X.", "O.X"]

Kết quả mong đợi:
expected = "X"
Đầu vào:
std::vector<std::string> board = {"XOX", ".X.", "O.X"};

Kết quả mong đợi:
std::string expected = "X";
Đầu vào:
string[] board = new string[] {"XOX", ".X.", "O.X"};

Kết quả mong đợi:
string expected = "X";

Giải thích

X holds the diagonal from top-left to bottom-right, so X wins.

Ví dụ 2
Đầu vào:
board = ["XOX", "XOO", "OXX"]

Kết quả mong đợi:
expected = "Draw"
Đầu vào:
std::vector<std::string> board = {"XOX", "XOO", "OXX"};

Kết quả mong đợi:
std::string expected = "Draw";
Đầu vào:
string[] board = new string[] {"XOX", "XOO", "OXX"};

Kết quả mong đợi:
string expected = "Draw";

Giải thích

The board is full and no line has three of a kind: Draw.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

Check every row, column, and the two diagonals for three identical non-empty marks.

Gợi ý 2

Track whether any empty cells remain while scanning the board once.

Gợi ý 3

Remember that a full board with no winner is a draw, otherwise it is pending.

Độ phức tạp mong đợi

O(1) time, O(1) extra space

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 Н"Никита "Programmer" Python 947 ms - 5/5 Xem code
2 LMLaura Mahlow Python 975 ms - 2/5 Xem code
3 PKPornchai Kaewkrabil Go 1,357 ms - 4/5 Xem code

Học hỏi từ người khác

Lời giải cộng đồng

Cảnh báo: Có 3 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem code của người khác và nhận xét của AI. Đăng nhập và giải thử thách để tham gia thảo luận.