Skip to content

Latest commit

 

History

History
41 lines (33 loc) · 1.2 KB

36.md

File metadata and controls

41 lines (33 loc) · 1.2 KB

Leetcode 36. 有效的数独

36. 有效的数独

/**
 * @param {character[][]} board
 * @return {boolean}
 */
var isValidSudoku = function (board) {
  //  生成三个空二维数组,分别用于判断行、列、3x3 子数独
  const isUsedInRow = new Array(9).fill().map(() => new Array());
  const isUsedInCol = new Array(9).fill().map(() => new Array());
  const isUsedInBox = new Array(9).fill().map(() => new Array());

  // 遍历数独九宫格
  for (let i = 0; i < 9; i++) {
    for (let j = 0; j < 9; j++) {
      const num = board[i][j]; // 当前处理的数字
      if (num == ".") { // . = 空,进行下一次循环
        continue;
      }

      const boxIndex = Math.floor(i / 3) + Math.floor(j / 3) * 3; // 生成 3x3 子数独内的索引值

      // 判断当前数字在行、列、3x3 子数独数组中是否存在
      if (isUsedInRow[i][num] || isUsedInCol[j][num] || isUsedInBox[boxIndex][num]) {
        return false;
      }

      // 将当前数字写入行、列、3x3 子数独数组中
      isUsedInRow[i][num] = true;
      isUsedInCol[j][num] = true;
      isUsedInBox[boxIndex][num] = true;
    }
  }
  return true;
};