No-Repeat Garden Beds

Mediumhash mapAlso known as Valid Sudoku

A community garden is a 9 by 9 grid of plots, split into nine 3 by 3 beds. There are nine kinds of plant, numbered 1 to 9. To stop pests spreading, no kind may appear twice in the same row, column or bed.

The planting plan is partly filled in, with 0 for an unclaimed plot. Check that what is planned so far breaks no rule.

Your task

Write validPlan(plots). plots is a 9 × 9 grid, plots[r][c] being the plant in row r, column c, or 0 if the plot is empty. Bed boundaries fall after rows 2 and 5 and after columns 2 and 5.

Return true if no plant number (1 to 9) appears twice in any row, column or bed, and false otherwise. Empty plots never break a rule. Only check the planned plots, not whether the empty ones could all be filled.

validPlan(plots: int[][]) → bool

Examples

Example 1
Input
plots = [[0, 2, 0, 0, 0, 0, 0, 0, 9], [0, 5, 6, 0, 8, 9, 1, 2, 0], [0, 0, 0, 1, 0, 0, 4, 0, 6], [0, 3, 4, 0, 0, 0, 0, 0, 0], [5, 6, 7, 0, 9, 1, 0, 3, 0], [0, 9, 0, 0, 0, 4, 0, 0, 7], [0, 0, 5, 0, 7, 8, 0, 0, 0], [6, 0, 8, 0, 1, 2, 0, 0, 0], [0, 1, 0, 3, 0, 0, 6, 7, 0]]
Output
true
Why

Each row, column and bed holds each plant at most once. Empty plots are fine.

Example 2
Input
plots = [[0, 2, 0, 0, 0, 0, 0, 0, 9], [0, 5, 6, 0, 8, 9, 1, 2, 0], [2, 0, 0, 1, 0, 0, 4, 0, 6], [0, 3, 4, 0, 0, 0, 0, 0, 0], [5, 6, 7, 0, 9, 1, 0, 3, 0], [0, 9, 0, 0, 0, 4, 0, 0, 7], [0, 0, 5, 0, 7, 8, 0, 0, 0], [6, 0, 8, 0, 1, 2, 0, 0, 0], [0, 1, 0, 3, 0, 0, 6, 7, 0]]
Output
false
Why

This is the first plan plus a 2 at row 2, column 0. Row 2 (1, 4, 6) and column 0 (5, 6) are fine, but the top-left bed already has a 2 at row 0, column 1.

Constraints

  • plots has exactly 9 rows, each with exactly 9 numbers.
  • 0 ≤ plots[r][c] ≤ 9
Start with brute force

For every planted plot, scan the rest of its row, column and bed for the same plant.

On a 9 × 9 grid that is about 81 × 24 checks, so speed is not a problem. The drawback is the code, which needs three scanning loops and careful bed boundaries, and on an n × n garden the work grows like n³. Recording each plant once in its three groups is shorter and faster.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code