No-Repeat Garden Beds

Mediumhash mapAlso known as Valid Sudoku

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

The planting plan is only partly filled in, with 0 for a plot nobody has claimed yet. Before the next work day, you want to check that what is already planned 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, any column or any bed, and false otherwise. Empty plots never break a rule. You only check the plots already planned, 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

Every row, every column and every bed holds each plant at most once. Plenty of plots are empty, and that is 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 with plant 2 added at row 2, column 0. Row 2 holds 1, 4 and 6, and column 0 holds 5 and 6, so both are fine. But that plot is in the top-left bed, which already has a 2 at row 0, column 1. The bed rule is broken.

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, its column and its bed, looking for the same plant.

On a 9 × 9 garden this is about 81 × 24 checks, which is small, so it is not too slow here. The real cost is the code: three different scanning loops, the fiddly bed bounds, and on a bigger n × n garden the work grows like n³. Recording each plant once in the right three groups is both 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