Tic-Tac-Toe with K Players
GoogleOnsiteMedium
Tic-tac-toe on an n x n board played by k players. Players are numbered 0 to k - 1 and play in that order, starting with player 0 and returning to player 0 after player k - 1.
Part 1: Play the game
Implement a class Game for tic-tac-toe played by k players on an n x n board. The constructor Game(n, k) starts with an empty board.
move(row, col) places the current player's mark in the cell at row, col (both counted from 0) and returns the state of the game as a string:
"Invalid"when the cell is outside the board, the cell already has a mark, or the game is already over. The board and the turn stay as they were."Player i wins"when the move gives playeriat least 3 of their marks in consecutive cells of one row, one column or one diagonal (in either diagonal direction). The game is then over."Draw"when the move fills the last empty cell without a win. The game is then over."In progress"otherwise, and the turn passes to the next player.
- Example 1
- init
[3,2]- operations
[["move",[0,0]],["move",[0,0]],["move",[1,0]],["move",[1,1]],["move",[0,1]],["move",[2,2]],["move",[2,0]]]- Output
["In progress","Invalid","In progress","In progress","In progress","Player 0 wins","Invalid"]
Why: Player 0 takes (0,0). Player 1 tries the same cell and gets
Invalid, so player 1 plays (1,0). Player 0 takes (1,1), player 1 takes (0,1), and player 0 takes (2,2), completing the main diagonal. Any later move isInvalid. - Example 2
- init
[3,2]- operations
[["move",[0,0]],["move",[0,1]],["move",[0,2]],["move",[1,1]],["move",[1,0]],["move",[1,2]],["move",[2,1]],["move",[-1,0]],["move",[2,0]],["move",[2,2]],["move",[0,0]]]- Output
["In progress","In progress","In progress","In progress","In progress","In progress","In progress","Invalid","In progress","Draw","Invalid"]
Why: Nine valid moves fill the board without three in a row, so the ninth returns
Draw. The earlier (-1,0) is off the board and returnsInvalidwithout using a turn, and the move after the end returnsInvalid.
Constraints
3 <= n <= 202 <= k <= 10- At most
n * n + 10calls tomove rowandcolare integers, possibly outside the board