← Questions

Connect Four board with gravity drops and board snapshots

0
SnowflakeCoding

Build the board for a gravity-based four-in-a-row game. Players drop single-character colored pieces into columns. A piece falls straight down and stops in the lowest empty cell of its column.

Implement ConnectFourBoard:

  • ConnectFourBoard(rows, cols) creates an empty board with rows rows and cols columns. Every cell starts as the character '0'. Row 0 is the top row, and row rows - 1 is the bottom.
  • drop(color, col) -> List[List[str]] drops a piece of color into column col, then returns the board after the move as a 2D list of characters.
    • color is any single character other than '0', for example 'R', 'Y' or 'G'.
    • If column col is already full, the board does not change, and you still return its current state.
    • The returned grid must be an independent copy. Changes the caller makes to it must not affect the board, and later drops must not change a grid returned earlier.
    • Raise an error if col is outside 0..cols-1.

Part 2. Add last_move_wins() -> bool. It returns true when the piece placed by the most recent successful drop forms a line of at least 4 pieces of its color: horizontal, vertical or diagonal. It returns false if the last drop hit a full column.

Constraints. 1 <= rows, cols <= 100. There are at most 10^4 calls to drop.

Example 1

b = ConnectFourBoard(3, 3)
b.drop('G', 2)  ->  [['0','0','0'],
                     ['0','0','0'],
                     ['0','0','G']]
b.drop('B', 2)  ->  [['0','0','0'],
                     ['0','0','B'],
                     ['0','0','G']]

Example 2

b = ConnectFourBoard(2, 2)
b.drop('G', 0)
b.drop('B', 0)
b.drop('G', 0)  ->  [['B','0'],
                     ['G','0']]   # column 0 is full, so nothing changes

Reconstructed from the reported question; details may differ from what interviewers ask.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding