leetcode 36. Valid Sudoku

来源:互联网 发布:oracle 数据库迁移 编辑:程序博客网 时间:2024/06/02 02:10

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.

Subscribe to see which companies asked this question

看看题目中这句话:A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
有效和有解不是一个意思,比如:
这里写图片描述
这是一个有效无解数独
要求是否有解真的是好难啊 指不定是什么NP难问题
所以没打开有效规则时吓了一跳
要求是否有效就很简单了
只要“每行 每列 每个九宫格”判断一下就可以了

public boolean isValidSudoku(char[][] board) {        for(int i = 0;i < board.length;i++){            HashSet<Character> set = new HashSet<Character>();            for(int j = 0;j < board.length;j++){                if(board[i][j] != '.' && set.contains(board[i][j]))                {                    System.out.println(i+" "+j+"行冲突");                    return false;                }                else                    set.add(board[i][j]);            }        }        for(int j = 0;j < board.length;j++){            HashSet<Character> set = new HashSet<Character>();            for(int i = 0;i < board.length;i++){                if(board[i][j] != '.' && set.contains(board[i][j]))                {                    System.out.println(i+" "+j+"列冲突");                    return false;                }                else                    set.add(board[i][j]);            }        }        for(int blockI = 0;blockI < board.length/3;blockI++){            for(int blockJ = 0;blockJ<board.length/3;blockJ++){                HashSet<Character> set = new HashSet<Character>();                for(int i = blockI*3;i<(blockI+1)*3;i++){                    for(int j = blockJ*3;j < (blockJ+1)*3;j++){                        if(board[i][j] != '.' && set.contains(board[i][j]))                        {                            System.out.println(i+" "+j+"块冲突");                            return false;                        }                        else                            set.add(board[i][j]);                    }                }            }        }        return true;    }
0 0
原创粉丝点击