[JavaScript 刷题] 矩阵 - 有效的数独, leetcode 36

Posted GoldenaArcher

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[JavaScript 刷题] 矩阵 - 有效的数独, leetcode 36相关的知识,希望对你有一定的参考价值。

[javascript 刷题] 矩阵 - 有效的数独, leetcode 36

github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。

题目地址:36. Valid Sudoku

题目

如下:

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

解题思路

数独应该都玩过,这道题问的就是当前数独是否是个合法的数独(不要求能有解)。

基本上考验的就是矩阵的遍历,判断每行,每列,每个九宫格是否为只包含 1-9 并且不存在重复数字即可。

使用 JavaScript 解题

/**
 * @param character[][] board
 * @return boolean
 */
var isValidSudoku = function (board) 
  // valid rows
  for (let i = 0; i < 9; i++) 
    const currRow = [];
    for (let j = 0; j < 9; j++) 
      if (board[i][j] === ".") continue;
      if (currRow[board[i][j]]) return false;
      currRow[board[i][j]] = true;
    
  

  for (let i = 0; i < 9; i++) 
    const currCol = [];
    for (let j = 0; j < 9; j++) 
      if (board[j][i] === ".") continue;
      if (currCol[board[j][i]]) return false;
      currCol[board[j][i]] = true;
    
  

  const checkForValidGrid = (r, c) => 
    const grid = [];
    for (let i = r; i < r + 3; i++) 
      for (let j = c; j < c + 3; j++) 
        if (board[i][j] === ".") continue;
        if (grid[board[i][j]]) return false;
        grid[board[i][j]] = true;
      
    

    return true;
  ;

  for (let i = 0; i < 9; i += 3) 
    for (let j = 0; j < 9; j += 3) 
      if (!checkForValidGrid(i, j)) return false;
    
  

  return true;
;

以上是关于[JavaScript 刷题] 矩阵 - 有效的数独, leetcode 36的主要内容,如果未能解决你的问题,请参考以下文章

leecode刷题-- 有效的数独

java刷题--36有效的数独

java刷题--36有效的数独

java刷题--36有效的数独

LeetCode刷题 36 有效的数独

Leetcode刷题100天—36. 有效的数独(数组+哈希)—day26