判定一个数独是否有效。

来源:互联网 发布:淘宝里猜你喜欢在哪里 编辑:程序博客网 时间:2024/06/14 03:07

/**
* Sudoku
* Created by Administrator on 2017/6/24.
* 请判定一个数独是否有效。
* 该数独可能只填充了部分数字,其中缺少的数字用 . 表示。
*/

class Solution {    /**      * @param board: the board        @return: wether the Sudoku is valid      */    private static final int SUDOKU = 9;    private static final int BLOCK = 3;    public boolean isValidSudoku(char[][] board) {        int row;        int col;        //分割为三个9*3的        int d = 0;        char[][] c_block = new char[SUDOKU * 3][SUDOKU];        for (int i = 0; i < SUDOKU; i++) {            for (int j = 0; j < SUDOKU; j++) {                row = j % BLOCK + d;                col = j / BLOCK + (i / BLOCK) * BLOCK;                c_block[i][j] = board[col][row];                c_block[SUDOKU + i][j] = board[i][j];                c_block[SUDOKU * 2 + i][j] = board[j][i];            }            d = (d + BLOCK) % SUDOKU;        }        return isRight(c_block);    }    private boolean isRight(char[][] chars){        int  row = chars[0].length;        Set<Character> set = new HashSet<Character>();        for (char[] aChar : chars) {            int count = 0;            for (int j = 0; j < row; j++) {                if (aChar[j] == '.') {                    count++;                    continue;                }                set.add(aChar[j]);            }            if (set.size() + count < 9) {                return false;            }            set.clear();        }        return true;    }};