Valid Sudoku

来源:互联网 发布:淘宝的车秒贷怎么样 编辑:程序博客网 时间:2024/06/02 18:16

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.

Show Tags
思路: 就是检查一遍里面的每个点是否合法.
易错点: 别忘了排除 同一个位置的。

public class Solution {    public boolean isValidSudoku(char[][] board) {        for(int i = 0; i < 9; i++){            for(int j = 0; j < 9; j++){                if(board[i][j] != '.'){                    if(!isValid(board, i, j))                        return false;                }            }        }        return true;    }        private boolean isValid(char[][] board, int x, int y){        char c = board[x][y];        for(int i = 0; i < 9; i++){            if(i != y && board[x][i] == c)                return false;            if(i != x && board[i][y] == c)                return false;            int blockRow = 3 * (x / 3) + i / 3;            int blockCol = 3 * (y / 3) + i % 3;            if((blockRow != x || blockCol != y) && board[blockRow][blockCol] == c)                return false;        }        return true;    }}


0 0