首页 > 代码库 > Valid Sudoku

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 ‘.‘.


A partially filled sudoku which is valid.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

方法

只需要判断每一行,每一列以及每一个小矩形里面没有重复的元素即可。如果是空着的,默认为正确的。
    private boolean isValidRow(char[][] board) {
        int len = 9;
        boolean[] status = new boolean[len];
        for (int i = 0; i < len; i++) {
            for (int k = 0; k < len; k++) {
                status[k] = false;
            }
            
            for (int j = 0; j < len; j++) {
                if (board[i][j] != '.') {
                    if (status[board[i][j] - '1']) {
                        return false;
                    } else {
                        status[board[i][j] - '1'] = true;
                    }
                }
            }
         
        }
        return true; 
    }
    
    
    private boolean isValidColumn(char[][] board) {
        int len = 9;
        boolean[] status = new boolean[len];
        for (int i = 0; i < len; i++) {
            for (int k = 0; k < len; k++) {
                status[k] = false;
            }
            
            for (int j = 0; j < len; j++) {
                if (board[j][i] != '.') {
                    if (status[board[j][i] - '1']) {
                        return false;
                    } else {
                        status[board[j][i] - '1'] = true;
                    }
                }
            }
        }
        return true;
    }  
    
    private boolean isValidBoxes(char[][] board) {
        int len = 9;
        boolean[] status = new boolean[len];
        for (int i = 0; i < len; i = i + 3) {
            for (int j = 0; j < len; j = j + 3) {
                for (int k = 0; k < len; k++) {
                    status[k] = false;
                }
                
                for (int p = 0; p < 3; p++) {
                    for (int q = 0; q < 3; q++) {
                        if (board[i + p][j + q] != '.') {
                            if (status[board[i + p][j + q] - '1']) {
                                return false;
                            } else {
                               status[board[i + p][j + q] - '1'] = true; 
                            }
                        }
                    }
                }
                
                
            }
        }
        
        return true;
    }
    public boolean isValidSudoku(char[][] board) {
        return isValidRow(board) && isValidColumn(board) && isValidBoxes(board);
    }