[leetcode 36][有效的数独]

有效的数独

  • 请你判断一个 9x9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。
    数字 1-9 在每一行只能出现一次。
    数字 1-9 在每一列只能出现一次。
    数字 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

class Solution {
    public boolean isValidSudoku(char[][] board) {
        for (int i = 0; i < board.length; i++) {
            ArrayList<Character> row = new ArrayList<>();
            ArrayList<Character> col = new ArrayList<>();
            ArrayList<Character> grid = new ArrayList<>();
            // 通过i,j坐标算出行、列、宫格三种坐标,用list判断重复
            for (int j = 0; j < board.length; j++) {
                // 行
                if (row.contains(board[i][j])) {
                    return false;
                }
                if (board[i][j] != '.') {
                    row.add(board[i][j]);
                }
                // 列
                if (col.contains(board[j][i])) {
                    return false;
                }
                if (board[j][i] != '.') {
                    col.add(board[j][i]);
                }
                // 3宫格
                int m = i / 3 * 3 + j / 3;
                int n = i % 3 * 3 + j % 3;
                if (grid.contains(board[m][n])) {
                    return false;
                }
                if (board[m][n] != '.') {
                    grid.add(board[ m][n]);
                }
            }
        }
        return true;
    }
}
上一篇:leetcode36.有效数独——leetcode每日一题2021.9.17


下一篇:adjacent_diffenerce