<AI/>
enru
Все статьи

Valid sudoku

LeetCode 36: Check whether a partially filled 9x9 Sudoku board is valid by tracking digits in rows, columns and boxes.

Сложность
Средняя
Опубликовано
Темы
#matrix#hash table
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

7 9 8 5 3 1 2 1 8 7 4 1 8 4 5 2 6 4 5 5 4 2 8 5 3 9 6 8

You are given a 9 x 9 Sudoku board. Determine whether the board is valid. Only the filled cells need to be validated according to the following rules.

  1. Each row must contain the digits 1 to 9 without repetition.
  2. Each column must contain the digits 1 to 9 without repetition.
  3. Each of the nine 3 x 3 boxes of the board must contain the digits 1 to 9 without repetition.

A (partially filled) Sudoku board can be valid but not necessarily solvable. Only the filled cells need to be validated according to the rules above.

Constraints

  • The board has 9 rows
  • The board has 9 columns
  • The values are digits 1 - 9 or "." for empty cells

Examples

Input

[
    ["5","3",".",".","7",".",".",".","."],
    ["6",".",".","1","9","5",".",".","."],
    [".","9","8",".",".",".",".","6","."],
    ["8",".",".",".","6",".",".",".","3"],
    ["4",".",".","8",".","3",".",".","1"],
    ["7",".",".",".","2",".",".",".","6"],
    [".","6",".",".",".",".","2","8","."],
    [".",".",".","4","1","9",".",".","5"],
    [".",".",".",".","8",".",".","7","9"],
]

Answer: true

Solution

First of all, to solve this problem we need a way to track the uniqueness of values in each row, column and box. For this we create several fixed-size helper structures that record which values have been used.

The trickiest part of the problem is understanding how these structures should work.

First, we define a fixed-size square matrix (an array of arrays) rows. Our matrix has 9 rows with 9 columns each.

How do we record that a digit is present in a row? For example, if row 1 contains the digit 3, we set rows[1][2] to true: the index i is the row index, and j is the digit's value - 1. So index zero in a row records the presence of digit 1, index one records digit 2, index two records digit 3, and so on. We use exactly the same approach to track values in columns, so we create a 9 x 9 matrix columns.

Detecting repeated digits in each box is a little more complicated, but not by much. First, let's mentally index each box of the board.

7 9 8 5 3 1 2 1 8 7 4 1 8 4 5 2 6 4 5 5 4 2 8 5 3 9 6 8 0 0 1 1 2 2 ← 1:1

For example, coordinate 1:1 is the middle box, and 2:2 is the bottom right one. Now we create a Hash Map called quads to store which digits occur in each box. The key is a string with the coordinate, and the value is an array of 9 elements, just like in the rows and columns matrices. So to record that, say, the middle box contains the digit 2, we create an array under the key 1:1 and set the element at index 1 to true.

Once this part is clear, the algorithm becomes very simple.

We go over all cells of the board and check only those that contain digits. If for the given digit all values in rows, columns and quads are false, the digit is unique so far. In that case we set all of them to true and move on to the next iteration.

If at least one of the structures already has true, the digit already exists and is not unique. In that case we can stop and return false.

If we go over the whole board without ever hitting true, all digits are unique and we return true.

By the way, to get the coordinates of a box, we just integer-divide the row and column indices by 3.

typescript
export const isValidSudoku = (board: string[][]): boolean => {
  const n = board.length;
 
  const rows: boolean[][] = [];
  const columns: boolean[][] = [];
  const quads: Record<string, boolean[]> = {};
 
  // Pre-fill the arrays with false values
  for (let i = 0; i < n; i++) {
    rows.push(new Array(n).fill(false));
    columns.push(new Array(n).fill(false));
  }
 
  for (let row = 0; row < n; row++) {
    for (let col = 0; col < n; col++) {
      if (board[row][col] === '.') {
        continue;
      }
 
      const pos = Number(board[row][col]) - 1;
      const key = `${Math.floor(row / 3)}:${Math.floor(col / 3)}`;
 
      if (!quads[key]) {
        quads[key] = new Array(n).fill(false);
      }
 
      if (rows[row][pos] || columns[col][pos] || quads[key][pos]) {
        return false;
      }
 
      rows[row][pos] = true;
      columns[col][pos] = true;
      quads[key][pos] = true;
    }
  }
 
  return true;
};

Complexity Analysis

Time Complexity

Since we go over the whole board, the traversal costs O(n2).

Space Complexity

  • The rows matrix takes n2.
  • The columns matrix takes n2.
  • The quads map takes n2.

In total we use 3 * n2 additional memory, so the overall complexity is O(n2).