LeetCode每日一题:valid sudoku

问题描述

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character'.'.

问题分析

判断数独是否合法,数独只需要满足每个小的九宫格里面的每一行每一列里1-9只出现一次,直接暴力求解即可。

代码实现

public boolean isValidSudoku(char[][] board) {
        if (board == null || board.length != 9 || board[0].length != 9)
            return false;
        for (int i = 0; i < 9; i++) {
            boolean[] map = new boolean[9];
            for (int j = 0; j < 9; j++) {
                if (board[i][j] != '.') {
                    if (map[(int) (board[i][j] - '1')]) {
                        return false;
                    }
                    map[(int) (board[i][j] - '1')] = true;
                }
            }
        }
        for (int j = 0; j < 9; j++) {
            boolean[] map = new boolean[9];
            for (int i = 0; i < 9; i++) {
                if (board[i][j] != '.') {
                    if (map[(int) (board[i][j] - '1')]) {
                        return false;
                    }
                    map[(int) (board[i][j] - '1')] = true;
                }
            }
        }
        for (int block = 0; block < 9; block++) {
            boolean[] map = new boolean[9];
            for (int i = block / 3 * 3; i < block / 3 * 3 + 3; i++) {
                for (int j = block % 3 * 3; j < block % 3 * 3 + 3; j++) {
                    if (board[i][j] != '.') {
                        if (map[(int) (board[i][j] - '1')]) {
                            return false;
                        }
                        map[(int) (board[i][j] - '1')] = true;
                    }
                }
            }
        }
        return true;
    }

你可能感兴趣的:(LeetCode每日一题:valid sudoku)