[LeetCode-Java]36. Valid Sudoku

来源:互联网 发布:java读取zip文件夹 编辑:程序博客网 时间:2024/05/21 23:01

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 ‘.’.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

解:利用set的元素唯一性来判断是否包含重复元素。

public boolean isValidSudoku(char[][] board) {        HashSet<Character> set = new HashSet<>();        //判断行        for (int i = 0;i<board[0].length;i++){            set.clear();            for (int j = 0;j<board.length;j++){                if (board[i][j] == '.') continue;                if (set.contains(board[i][j])) return false;                set.add(board[i][j]);            }        }        //判断列        for (int j = 0;j<board.length;j++){            set.clear();            for (int i = 0;i<board[0].length;i++){                if (board[i][j] == '.') continue;                if (set.contains(board[i][j])) return false;                set.add(board[i][j]);            }        }        //判断九宫格        for(int i = 0; i < board.length - 2; i = i+3){//行{            for(int j = 0; j < board[0].length - 2; j=j+3){                set.clear();                for(int m = i; m < i + 3;m++){                    for(int n = j; n < j+3; n++){                        if (board[m][n] == '.') continue;                        if (set.contains(board[m][n])) return false;                        set.add(board[m][n]);                    }                }            }        }        return true;    }
0 0