列表

详情


36. 有效的数独

请你判断一个 9 x 9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。

  1. 数字 1-9 在每一行只能出现一次。
  2. 数字 1-9 在每一列只能出现一次。
  3. 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)

 

注意:

 

示例 1:

输入: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"]]
输出:true

示例 2:

输入:board = 
[["8","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"]]
输出:false
解释:除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。 但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。

 

提示:

相似题目

解数独

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { } };

python3 解法, 执行用时: 53 ms, 内存消耗: 16.4 MB, 提交时间: 2024-04-20 16:19:15

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        # 0: row, 1: column, 2: square
        record = {0:defaultdict(set), 1:defaultdict(set), 2:defaultdict(set)}
        n = len(board)
        m = sqrt(n)
        for i in range(n):
            for j in range(n):
                if board[i][j] == '.':
                    continue
                if board[i][j] in record[0][i] or board[i][j] in record[1][j]:
                    return False
                sq = i // m * m + j // m
                if board[i][j] in record[2][sq]:
                    return False
                record[0][i].add(board[i][j])
                record[1][j].add(board[i][j])
                record[2][sq].add(board[i][j])
        return True

cpp 解法, 执行用时: 16 ms, 内存消耗: 22.4 MB, 提交时间: 2024-04-20 16:18:48

class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        int rows[9][9];
        int columns[9][9];
        int subboxes[3][3][9];
        
        memset(rows,0,sizeof(rows));
        memset(columns,0,sizeof(columns));
        memset(subboxes,0,sizeof(subboxes));
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                char c = board[i][j];
                if (c != '.') {
                    int index = c - '0' - 1;
                    rows[i][index]++;
                    columns[j][index]++;
                    subboxes[i / 3][j / 3][index]++;
                    if (rows[i][index] > 1 || columns[j][index] > 1 || subboxes[i / 3][j / 3][index] > 1) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
};

javascript 解法, 执行用时: 93 ms, 内存消耗: 54.8 MB, 提交时间: 2024-04-20 16:18:27

/**
 * @param {character[][]} board
 * @return {boolean}
 */
var isValidSudoku = function(board) {
    const rows = new Array(9).fill(0).map(() => new Array(9).fill(0));
    const columns = new Array(9).fill(0).map(() => new Array(9).fill(0));
    const subboxes = new Array(3).fill(0).map(() => new Array(3).fill(0).map(() => new Array(9).fill(0)));
    for (let i = 0; i < 9; i++) {
        for (let j = 0; j < 9; j++) {
            const c = board[i][j];
            if (c !== '.') {
                const index = c.charCodeAt() - '0'.charCodeAt() - 1;
                rows[i][index]++;
                columns[j][index]++;
                subboxes[Math.floor(i / 3)][Math.floor(j / 3)][index]++;
                if (rows[i][index] > 1 || columns[j][index] > 1 || subboxes[Math.floor(i / 3)][Math.floor(j / 3)][index] > 1) {
                    return false;
                }
            }
        }
    }
    return true;
};

java 解法, 执行用时: 1 ms, 内存消耗: 43.4 MB, 提交时间: 2024-04-20 16:18:14

class Solution {
    public boolean isValidSudoku(char[][] board) {
        int[][] rows = new int[9][9];
        int[][] columns = new int[9][9];
        int[][][] subboxes = new int[3][3][9];
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                char c = board[i][j];
                if (c != '.') {
                    int index = c - '0' - 1;
                    rows[i][index]++;
                    columns[j][index]++;
                    subboxes[i / 3][j / 3][index]++;
                    if (rows[i][index] > 1 || columns[j][index] > 1 || subboxes[i / 3][j / 3][index] > 1) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
}

golang 解法, 执行用时: 0 ms, 内存消耗: 2.8 MB, 提交时间: 2021-07-17 11:59:29

func isValidSudoku(board [][]byte) bool {
    row := make([][]bool, 9)
    col := make([][]bool, 9)
    box := make([][]bool, 9)
    var num, boxIndex int
    for i := 0; i < 9; i++ {
        row[i] = make([]bool, 9)
        col[i] = make([]bool, 9)
        box[i] = make([]bool, 9)
    }

    for i := 0; i < 9; i++ {
        for j := 0; j < 9; j++ {
            if board[i][j] != '.' {
                num = int(board[i][j] - '1')
                boxIndex = (i / 3) * 3 + j / 3
                if row[i][num] || col[j][num] || box[boxIndex][num] {
                    return false
                }
                row[i][num] = true
                col[j][num] = true
                box[boxIndex][num] = true
            }
        }
    }
    return true
}

golang 解法, 执行用时: 4 ms, 内存消耗: 2.6 MB, 提交时间: 2021-07-17 11:00:37

func isValidSudoku(board [][]byte) bool {
    wow := make([]int, 9)
    var mux1, mux2, mux3, box_index int
    for i := 0; i < 9; i++ {
    	for j := 0; j < 9; j++ {
    		if board[i][j] == '.' {
    			continue
    		}
    		mux1 = 0x01 << (board[i][j] - '1')
            mux2 = 0x01 << 9 << (board[i][j] - '1')
            mux3 = 0x01 << 9 << 9 << (board[i][j] - '1')
            box_index = (i/3) * 3 + j/3;
            if (wow[i] & mux1) != mux1 && (wow[j] & mux2) != mux2 && (wow[box_index] & mux3) != mux3 {
                    wow[i] = wow[i] | mux1
                    wow[j] = wow[j] | mux2
                    wow[box_index] = wow[box_index] | mux3
            } else {
            	return false
            }
    	}
    }
    return true
}

上一题