439. Validate Chessboard Colours
Asked in
Validate Chessboard Colours

A square chessboard is painted using two colours, represented by 0 and 1. The board is provided as a list of comma-separated row strings.

Determine whether the board is valid. A chessboard is valid when every pair of cells that share a side have different colours.

Class

ChessboardValidator

Constructor

ChessboardValidator

ChessboardValidator()

  • Creates a new chessboard validator.

Method

isValidChessboard

public boolean isValidChessboard(List<String> board)

  • board.get(row) contains the comma-separated colours in the row at zero-based position row.
  • Returns true if every side-adjacent pair of cells have different colours.
  • Returns false otherwise.

Rules

  • Two cells are adjacent only when they share a horizontal or vertical side.
  • Cells that touch only at a corner are not adjacent.
  • Either colour may appear in the top-left cell.
  • A board containing only one cell is valid.
  • The input list must not be modified.

Constraints

  • 1 ≤ board.size() ≤ 1,000
  • Let n = board.size().
  • Every row contains exactly n values separated by commas, so the board has n rows and n columns.
  • Every cell value is either 0 or 1.
  • board and all its elements are non-null.

Expected Efficiency

  • The method should run in O(n2) time.
  • The method should use O(1) additional space.

Deterministic Output

The method returns only a boolean value. It returns true exactly when the complete board satisfies the adjacency rule.

Examples

Example 1

isValidChessboard( board = List.of( "1,0,1,0", "0,1,0,1", "1,0,1,0", "0,1,0,1"))

Output: true

Every horizontal and vertical neighbor has the opposite colour.

Example 2

isValidChessboard( board = List.of( "0,1,0", "1,0,1", "0,1,1"))

Output: false

The cells at positions (2, 1) and (2, 2) share a side and both have colour 1.

Example 3

isValidChessboard(board = List.of("0"))

Output: true

A one-cell board has no adjacent pair that can violate the rule.



Please use Laptop/Desktop or any other large screen to add/edit code.