KatInterview

Per-Move Win Tracker for a Square Noughts-and-Crosses Grid

Arrays & HashingAuto-graded · 25 test cases
MediumAuto-gradedArrays & Hashingsimulationcountingmatrix

Last updated

Replay a sequence of marks on an n-by-n grid and report after each one whether the mover has completed a row, column or diagonal, using per-line counters.

Square Grid Game Replay

Two players, numbered 1 and 2, take part in a game on a square grid with n rows and n columns. Each turn, a player puts their mark in a cell that is currently unoccupied. A player wins the moment one of the following is made up entirely of their own marks:

  • any full row,
  • any full column,
  • the main diagonal,
  • the anti-diagonal.

You are given the grid size and the list of placements in the order they happen. After each placement, report whether someone has won.

Task

Implement a function that takes n and moves, and returns a list with one integer per placement, in the same order.

Each entry moves[i] = [row, col, player] says that player marks the cell at 0-indexed position (row, col).

Definitions and rules

  • The main diagonal consists of the cells (i, i) for 0 <= i < n.
  • The anti-diagonal consists of the cells (i, n - 1 - i) for 0 <= i < n.
  • The value reported after a placement is the number of the player who has won, or 0 if there is no winner yet. Only the player who just moved can have just won.
  • Apply the placements exactly in the order given. Players are not required to alternate, so do not check whose turn it is.
  • When n is odd, the center cell belongs to both diagonals.
  • The game stops at the first winning placement, so only the final entry of the result can be nonzero.
  • Return exactly one value per placement.

Constraints

  • 2 <= n <= 100
  • 1 <= len(moves) <= n * n
  • 0 <= row, col < n
  • No two placements use the same cell.
  • player is either 1 or 2.
  • No placement follows a winning placement.

Examples

Example 1

Input: grid_game_results(3, [[1, 1, 1], [0, 0, 2], [0, 2, 1], [2, 0, 2], [1, 0, 1], [2, 2, 2], [1, 2, 1]])

Output: [0, 0, 0, 0, 0, 0, 1]

Example 2

Input: grid_game_results(2, [[0, 1, 2], [1, 1, 1], [1, 0, 2]])

Output: [0, 0, 2]

Example 3

Input: grid_game_results(4, [[0, 0, 2], [0, 1, 1], [1, 1, 2], [0, 2, 1], [2, 2, 2]])

Output: [0, 0, 0, 0, 0]

Hints

Hint 1

After a placement at (r, c), which lines could possibly have become complete? Rescanning the whole grid is unnecessary.

Hint 2

For each line, keep how many marks each player owns on it. A line is full for a player exactly when that player's count equals n, because cells are never reused.

Hint 3

A cell can sit on the main diagonal (r == c), the anti-diagonal (r + c == n - 1), both (the center when n is odd), or neither. Test the two diagonals with separate if statements.