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);
    }


posted on 2017-07-15 12:10  ljbguanli  阅读(104)  评论(0编辑  收藏  举报