Connect-K Drop
MediumOnline Assessment
Referee a game of Connect-K and report how it stands.
Two players, "X" and "O", drop discs into a board with rows rows and cols columns; X moves first and they alternate. moves lists the column (numbered from 0) chosen on each turn. A disc falls to the lowest empty cell of its column.
- A move is invalid if the column does not exist (
< 0or>= cols) or is already full. An invalid move places nothing, and the player forfeits that turn: it is the opponent's turn next. - After a valid move, look at the four straight lines through the new disc (horizontal, vertical and both diagonals). The mover wins if in any of these lines the unbroken run of the mover's discs that contains the new disc has length exactly
k. A longer run does not count: withk = 3, joining two groups into a run of five is not a win. - The game ends at the first win, or when the board is full with no winner (a draw). All later entries of
movesare ignored. Ifmovesruns out first, the game is still open.
Input: rows, cols, k, moves.
Output: [status, board]. status is "X" or "O" for the winner, "draw", or "open". board lists the rows from top to bottom as strings of length cols, using "X", "O" and "." for an empty cell.
Example 1
- Input:
- [6,7,4,[0,0,1,1,2,2,3,4]]
- Output:
- ["X",[".......",".......",".......",".......","OOO....","XXXX..."]]
- Explanation
- X and O alternate; X fills the bottom row at columns 0, 1, 2 while O stacks on top of each. X's disc in column 3 makes a horizontal run of exactly 4, so X wins on the seventh move and the final entry (4) is ignored.
Example 2
- Input:
- [1,9,3,[0,8,1,6,3,5,4,7,2]]
- Output:
- ["draw",["XXXXXOOOO"]]
- Explanation
- One row, nine columns, k = 3. X ends with discs on 0, 1, 2, 3, 4 (a run of five, not a win) and O on 5, 6, 7, 8 (a run of four, not a win). The board fills up with no winner, so it is a draw.
Example 3
- Input:
- [4,4,4,[0,1,1,2,3,2,5,3,2,3,3]]
- Output:
- ["X",["...X","..XO",".XOO","XOOX"]]
- Explanation
- On a 4x4 board with k = 4, the entry 5 is not a column, so X forfeits that turn and O moves next (column 3). The remaining entries alternate from there and X completes the diagonal from the bottom-left to the top-right corner with the last disc in column 3.
Constraints
- 1 ≤ rows ≤ 8; 1 ≤ cols ≤ 9; 1 ≤ k ≤ 9
- 0 ≤ moves.length ≤ 100; -3 ≤ moves[i] ≤ cols + 2