Valid Sudoku Checker - A JavaScript Solution #leetcode 36

Valid Sudoku Checker - A JavaScript Solution #leetcode 36

Introduction: In this blog post, we will explore a JavaScript solution to determine the validity of a Sudoku puzzle. We will analyze the given code and explain its functionality step by step. Let's dive in!

leetcode

Problem: Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.

  2. Each column must contain the digits 1-9 without repetition.

  3. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.

  • Only the filled cells need to be validated according to the mentioned rules.

/**
 * @param {character[][]} board
 * @return {boolean}
 */
var isValidSudoku = function(board) {
  const N = board.length;
  const rows = new Map();
  for (let i = 0; i < 9; i++) {
    rows.set(i, new Set());
  }
  const cols = new Map();
  for (let i = 0; i < 9; i++) {
    cols.set(i, new Set());
  }
  const squares = new Map();
  for (let i = 0; i < 9; i++) {
    for (let j = 0; j < 9; j++) {
      let sqKey = getKey(i, j);
      squares.set(sqKey, new Set());
    }
  }

  for (let row = 0; row < N; row++) {
    for (let col = 0; col < N; col++) {
      let sqKey = getKey(row, col);
      if (board[row][col] === ".") continue;

      if (rows.get(row).has(board[row][col]) ||
        cols.get(col).has(board[row][col]) ||
        squares.get(sqKey).has(board[row][col])) {
        return false;
      }

      rows.get(row).add(board[row][col]);
      cols.get(col).add(board[row][col]);
      squares.get(sqKey).add(board[row][col]);
    }
  }
  return true;
};

const getKey = (row, col) => {
  let r = Math.floor(row / 3);
  let c = Math.floor(col / 3);
  let sqKey = "(" + String(r) + ", " + String(c) + ")";
  return sqKey;
}

You can test the code using a javascript console like below: It should return true.

let board = [
  ["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"]
];

console.log(isValidSudoku(board))

Code Explanation:

The function isValidSudoku, which takes a 2-dimensional character array representing a Sudoku board and returns a boolean value indicating whether the board is valid.

  1. Setting up the Data Structures: The code begins by initializing three maps, rows, cols, and squares. These maps will be used to track the presence of numbers in rows, columns, and 3x3 squares respectively. Each map is populated with keys ranging from 0 to 8, corresponding to the row or column index.

  2. Iterating through the Sudoku Board: Next, the code uses nested loops to iterate over each cell of the Sudoku board. For each cell, it checks if the value is a period (".") which indicates an empty cell. If it is, the iteration continues to the next cell.

  3. Validating the Current Cell: If the current cell is not empty, the code retrieves the corresponding square key using the getKey helper function. It then performs the following checks:

    • If the current number already exists in the same row, column, or square, the Sudoku board is invalid, and the function returns false.

    • If the number is not present, it is added to the respective row, column, and square sets to track its occurrence.

  4. Returning the Result: After iterating through the entire Sudoku board, if no conflicts are found, the function returns true, indicating that the Sudoku puzzle is valid.

Helper Function: getKey The code includes a helper function called getKey, which takes a row and column index and returns a string representing the square key. This key is used to identify the 3x3 square to which a cell belongs.

Conclusion: In this blog post, we have examined a JavaScript solution for validating a Sudoku puzzle using the provided code. By leveraging data structures such as maps and sets, the code efficiently checks for conflicts in rows, columns, and squares. Understanding and implementing this solution can be helpful when working with Sudoku puzzles or similar grid-based games.

Thank you for reading, and happy coding!

Note: The given code assumes the correctness of the Sudoku board's dimensions and values. Additional error handling and input validation may be necessary for real-world scenarios.