Dot grid game winner
I was asked this
No reports yet. Sign in to say where you were asked it.
Two players play a dots-and-boxes style game on a 9 x 9 grid of dots. The grid has 8 x 8 = 64 unit squares ("boxes"). Rows and columns are numbered 0 to 8.
You are given moves, a list of the sticks placed in order. moves[i] = [r1, c1, r2, c2] places a stick between dot (r1, c1) and dot (r2, c2). The two dots are always horizontally or vertically adjacent, and they may appear in either order.
Players strictly alternate. Player 1 makes moves 1, 3, 5, ... and player 2 makes moves 2, 4, 6, ..., whether or not a move closes a box. Whoever places the fourth side of a box scores that box. A single stick can close two boxes at once, and both count for its player.
Implement find_winner(moves: list[list[int]]) -> int. Return 1 or 2 for the player who owns more boxes after all moves, or 0 for a tie.
Constraints
-
0 <= len(moves) <= 144(the total number of sticks on a 9 x 9 dot grid) 0 <= r1, c1, r2, c2 <= 8- No stick is placed twice. (A natural follow-up asks you to validate this yourself.)
Example 1
moves = [[0,0,0,1], [0,0,1,0], [1,0,1,1], [0,1,1,1]]
output: 2
The first four sticks are the four sides of the top-left box. The 4th move is player 2's, so player 2 scores 1 and player 1 scores 0.
Example 2
moves = [[0,1,0,0], [5,5,5,6], [1,0,0,0], [6,6,6,7], [1,1,1,0], [7,7,7,8], [1,1,0,1]]
output: 1
Player 1's sticks (moves 1, 3, 5, 7) are the four sides of the top-left box, written with the endpoints reversed. Player 1 places the last side on move 7. Player 2's sticks close nothing.
Expected: O(1) work per move.
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
