Run-of-K Grid Game Simulator for Many Players
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate an N x N, M-player connect-K game with turn order, move validation, win detection from the last move, board snapshots and undo.
Run-of-K Grid Game Simulator
You are simulating a turn-based game on a square board with n rows and n columns. There are m players, numbered 1 to m. Players take turns in the fixed cycle 1, 2, ..., m, 1, 2, ..., and player 1 goes first. A player wins by owning at least k consecutive cells in a straight line: horizontal, vertical, diagonal or anti-diagonal.
Instead of building a class, you write one function that receives the game settings and a list of operations, runs them in order on a fresh game, and returns the result of each operation.
Inputs
n: the board side length.m: the number of players.k: the length of the run needed to win.operations: a list of strings. Each is"move","getBoardState"or"undo".arguments: a list of the same length asoperations. Entryiholds the arguments foroperations[i]:- for
"move"it is[row, col, player_id](rows and columns are 0-indexed); - for
"getBoardState"and"undo"it is an empty list.
- for
Operations
The board starts empty, with every cell 0. A cell holding player p's mark stores the value p. Each operation appends one entry to the output list.
move: player player_id tries to mark cell (row, col). Check the conditions in this order:
- If the game is already finished, the result is
-2. - If
(row, col)is outside the board, the result is-1. - If the cell is already occupied, the result is
-1. - If
player_idis not the player whose turn it is, the result is-1.
A rejected move changes nothing. Otherwise the mark is placed and the turn passes to the next player in the cycle.
- If the placed mark is part of a straight run of at least
kcells owned by the same player, that player wins. The game becomes finished and the result is1. - Otherwise the result is
0. If the board is now completely full, the game also becomes finished (a draw).
A game is finished when someone has won or the board is full. While it is finished, every move returns -2, even one that would otherwise be invalid.
getBoardState: the result is a snapshot of the board as a list of n rows, each a list of n integers. It is a copy, so later moves do not change it.
undo: reverts the most recent successfully placed mark.
- If no mark is currently on the board from valid moves (nothing to undo), the result is
-1and nothing changes. - Otherwise the cell is cleared, the turn returns to the player who made that move, the game is no longer finished, and the result is
0. Undo can be repeated to step back through earlier moves.
Any other operation name produces -1.
Output
Return a list with one result per operation, in order. Each result is an integer (1, 0, -1, -2) or, for getBoardState, a 2D list of integers.
Constraints
n,mandkare positive integers.kmay be larger thann. In that case nobody can win, and the game ends only when the board is full.player_id,rowandcolin amovecan be any integers, including values outside the valid ranges.len(operations) == len(arguments).- A run counts only if its cells are adjacent along one of the four line directions and all belong to the same player. Longer runs than
kalso count as a win.
Examples
Example 1
Input: simulate_connect_k_game(3, 2, 3, ['move', 'move', 'move', 'move', 'move'], [[0, 0, 1], [1, 1, 2], [0, 1, 1], [2, 2, 2], [0, 2, 1]])
Output: [0, 0, 0, 0, 1]
Example 2
Input: simulate_connect_k_game(1, 2, 1, ['move', 'getBoardState', 'undo', 'getBoardState', 'move'], [[0, 0, 1], [], [], [], [1, 1, 1]])
Output: [1, [[1]], 0, [[0]], -1]
Example 3
Input: simulate_connect_k_game(1, 1, 1, ['move', 'move', 'undo', 'move'], [[0, 0, 1], [0, 0, 1], [], [0, 0, 1]])
Output: [1, -2, 0, 1]
Hints
Hint 1
Keep the board, a stack of placed moves, whose turn it is, and a finished flag. Process the operations one at a time against this state.
Hint 2
A new winning run must pass through the cell just placed, since the game stops at the first win. From that cell, count same-player neighbours in both opposite directions along each of the 4 line orientations, and compare 1 + both counts with k.
Hint 3
For undo, pop the last move, clear its cell, set the turn back to that move's player and clear the finished flag. Remember that a full board also finishes the game, and that a winning move does not change the order of validation checks.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Simulate the game directly while keeping a small amount of state:
board: ann x ngrid with0for empty and the player number otherwise.history: a stack of(row, col, player)for every accepted move.current_player: whose turn it is.finished: whether the game is over (a win or a full board).
For each operation:
- move: check the conditions in the required order (finished, out of bounds, occupied or wrong player). If the move is accepted, place the mark, push it on the history and test for a win. The turn then advances to
current_player % m + 1. If the move wins, setfinishedand return1. Otherwise return0, and setfinishedif the board is now full. - getBoardState: return a copy of every row.
- undo: if the history is empty return
-1. Otherwise pop the last move, clear its cell, give the turn back to that move's player, clearfinishedand return0. - Any other operation returns
-1.
Win check
The game stops at the first win, so before a move there is no winning run on the board. Any new run of length k must therefore contain the cell just placed. For each of the four orientations (horizontal, vertical, diagonal, anti-diagonal), walk outward from the cell in both opposite directions while the cells belong to the same player. The total run length is 1 + forward + backward, and the move wins if that is at least k for any orientation.
Per-row and per-column counters would not work here, because the required run is k consecutive cells and k can be smaller than n. A local scan handles this correctly.
Why undo is correct
Only the last move can be the winning move or the one that filled the board, because play stops right after either. Undoing that move therefore always makes the game playable again, so clearing finished on every undo is safe. Restoring the turn to the undone move's player keeps the cycle consistent.
Complexity
- Each
movetakes O(min(k, n)) time (four orientations, each scanning at most aboutncells in both directions). Eachundotakes O(1). EachgetBoardStatetakes O(n^2) for the copy. - Space is O(n^2) for the board plus O(number of moves) for the history.
Reference solution
from typing import List
def simulate_connect_k_game(n: int, m: int, k: int, operations: List[str], arguments: List[List[int]]) -> List[object]:
board = [[0] * n for _ in range(n)]
history = []
current_player = 1
finished = False
results = []
def has_won(row, col, player):
directions = ((1, 0), (0, 1), (1, 1), (1, -1))
for dr, dc in directions:
count = 1
for sign in (1, -1):
r, c = row + sign * dr, col + sign * dc
while 0 <= r < n and 0 <= c < n and board[r][c] == player:
count += 1
r += sign * dr
c += sign * dc
if count >= k:
return True
return False
for operation, args in zip(operations, arguments):
if operation == "move":
row, col, player = args
if finished:
results.append(-2)
elif not (0 <= row < n and 0 <= col < n):
results.append(-1)
elif board[row][col] != 0 or player != current_player:
results.append(-1)
else:
board[row][col] = player
history.append((row, col, player))
if has_won(row, col, player):
finished = True
results.append(1)
else:
results.append(0)
if len(history) == n * n:
finished = True
current_player = current_player % m + 1
elif operation == "getBoardState":
results.append([r[:] for r in board])
elif operation == "undo":
if not history:
results.append(-1)
else:
row, col, player = history.pop()
board[row][col] = 0
current_player = player
finished = False
results.append(0)
else:
results.append(-1)
return results