36. Valid Sudoku

来源:互联网 发布:算法和程序的关系 编辑:程序博客网 时间:2024/06/16 06:05

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.

判断数独的合法性。

本题要求只判断已经填充的单元,只要已经填充的单元是合法的即可,与数独是否有解无关。

数独的合法性只需判断一下三条:

1、单行无重复

2、单列无重复

3、每个宫合法(宫的单位为9个格子,如上图中单个加黑的9个格子为一宫)

程序如下:

class Solution {    public boolean isValidSudoku(char[][] board) {        int row = board.length, col = board[0].length;        Set<Character> set = new HashSet<>();        Set<Character> colSet = new HashSet<>();        Set<Character> blockSet = new HashSet<>();        for (int i = 0; i < row; i ++){            set.clear();            for (int j = 0; j < col; ++ j){                if (board[i][j] == '.'){                    continue;                }                if (set.contains(board[i][j])){                    return false;                }                set.add(board[i][j]);                colSet.clear();                blockSet.clear();// check col and block                for (int m = 0; m < row; m ++){                    if (board[m][j] != '.'){                        if (colSet.contains(board[m][j])){                            return false;                        }                        colSet.add(board[m][j]);                    }                                        if (board[3*(i/3) + m/3][3*(j/3) + (m%3)] != '.'){                        if (blockSet.contains(board[3*(i/3) + m/3][3*(j/3) + (m%3)])){                            return false;                        }                        blockSet.add(board[3*(i/3) + m/3][3*(j/3) + (m%3)]);                    }                }            }        }        return true;    }}