[leetcode]Valid Sudoku

新博文跟本文算法一样,为了习惯 -> 新博文地址:[leetcode]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.

这道题不会,最后几乎全是copy这位大神的算法。菜比了,不会玩数独,也不知道这里所谓的valid是指开盘的摆法合法?还是指这盘数独有解?不过看了上面的算法,答案是指前者,是不是说只要开盘时的摆法合法,则必有解?如果不一定,那么,死局怎么能叫valid呢?

不管了,具体到这道题,这需要检查开局的摆法是否合法,这个相对比较简单,比较费脑的是block的下标略风骚。还是有必要记一下的,直接看代码吧。

	public boolean isValidSudoku(char[][] board){
        boolean [][] rows=new boolean[9][9];
        boolean [][] cols=new boolean[9][9];
        boolean [][] blocks=new boolean[9][9];
        for (int i = 0; i < 9; ++i) {  
            for (int j = 0; j < 9; ++j) {
                int c = board[i][j] - '1';
                if (board[i][j] == '.') continue;  
                if (rows[i][c] || cols[j][c] || blocks[i - i % 3 + j / 3][c])  
                    return false;  
                rows[i][c] = cols[j][c] = blocks[i - i % 3 + j / 3][c] = true;  
            }  
        }  
        return true;  
    }

 

 

你可能感兴趣的:(LeetCode)