← 返回 walmartlabs 的题目列表Validate Nonogram Solution
类型:qbank
Given a binary matrix of `B` (black) / `W` (white) cells plus a per-row and per-column list of black-run lengths, verify that the matrix is a valid solution to the nonogram puzzle described by those run lists.
Requirements
Input: matrix: char[][] with 'B' (filled) / 'W' (empty); rows: int[][] of length equal to matrix.length giving the expected consecutive black-run lengths in each row; columns: int[][] of length equal to matrix[0].length giving the expected consecutive black-run lengths in each column.
Return true iff every row's actual black-run sequence equals rows[i] and every column's actual black-run sequence equals columns[j].
An empty list [] means "the row / column should be entirely white."
Examples
matrix = [['W','W','W','W'],
['B','W','W','W'],
['B','W','B','B'],
['W','W','B','W'],
['B','B','W','W']]
rows = [[], [1], [1,2], [1], [2]]
columns = [[2,1], [1], [2], [1]]
→ true
rows = [[], [], [1], [1], [1,1]]
columns = [[2], [1], [2], [1]]
→ false (rows don't match the matrix)
Notes
Reduce each row and each column to its run-length list by scanning once and pushing a new run length whenever the current cell is 'B' and either the index is 0 or the previous cell is 'W'; increment the current run otherwise. Compare against the expected list.
Iterate columns by indexing matrix[i][j] rather than transposing — transposition allocates O(n²) extra and is the most common TLE / memory hit on large inputs.
Validate dimensions up front: rows.length == matrix.length, columns.length == matrix[0].length. The reported variant supplied two rows / columns pairs to test the same matrix, so factor the validation into a helper valid(matrix, rows, columns) and call it twice rather than duplicating loops.
Handle the empty-row case: an empty list must correspond to a fully white row / column; a single non-empty cell breaks the match.
Preparation
Hand-trace a 5×4 example before coding — the off-by-one between "black starts a new run" and "black extends the current run" is the dominant bug.
Write the row-side scan as a generic helper List<Integer> runs(char[] line), then reuse it for columns by passing matrix[*][j] slices.
Add stress tests for fully-white inputs, fully-black inputs, and asymmetric row / column counts to catch missing dimension checks.