36.有效的数独
链接:36.有效的数独
难度:Medium
标签:数组、哈希表、矩阵
简介:请你判断一个 9x9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。 。
题解 1 - javascript
- 编辑时间:2021-09-17
- 执行用时:96ms
- 内存消耗:43.8MB
- 编程语言:javascript
- 解法介绍:逐行遍历,set 储存。
function isValidSudoku(board: string[][]): boolean {
        const rows: Set<string>[] = new Array(9).fill(0).map(_ => new Set<string>());
        const cols: Set<string>[] = new Array(9).fill(0).map(_ => new Set<string>());
        const blocks: Set<string>[] = new Array(9).fill(0).map(_ => new Set<string>());
        const getBolck = (row: number, col: number) => ~~(row / 3) * 3 + ~~(col / 3);
        for (let row = 0; row < 9; row++) {
          for (let col = 0; col < 9; col++) {
            const val = board[row][col];
            const block = getBolck(row, col);
            if (val === '.') continue;
            const rowSet = rows[row];
            const colSet = cols[col];
            const blockSet = blocks[block];
            if (rowSet.has(val) || colSet.has(val) || blockSet.has(val)) return false;
            rowSet.add(val);
            colSet.add(val);
            blockSet.add(val);
          }
        }
        return true;
      }