Valid Sudoku

https://oj.leetcode.com/problems/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.

解题思路:

根据上面对于sudoku的定义,能够写出来。只要对每行和没列,以及九个小格子,都申明一个set,然后把不是'.'的格子中的值都放入set中,如果有重复就说明不是sudoku。

这里将行和列的check放一起,小格子的check单独列开了。需要注意的是,每个set申明的地方。第二个四重循环可能会有点晕。

public class Solution {

    public boolean isValidSudoku(char[][] board) {

        //同时check行和列

        for(int i = 0; i < board.length; i++){

            Set<Character> lineSet = new HashSet<Character>();

            Set<Character> coloumnSet = new HashSet<Character>();

            for(int j = 0; j < board[0].length; j++){

                if(board[i][j] != '.'){

                    if(board[i][j] < '0' || board[i][j] > '9'){

                        return false;

                    }

                    if(lineSet.contains(board[i][j])){

                        return false;

                    }else{

                        lineSet.add(board[i][j]);

                    }

                }

                if(board[j][i] != '.'){

                    if(board[j][i] < '0' || board[j][i] > '9'){

                        return false;

                    }

                    if(coloumnSet.contains(board[j][i])){

                        return false;

                    }else{

                        coloumnSet.add(board[j][i]);

                    }

                }

            }

        }

        

        //check九个小格子

        for(int i = 0; i < 9; i = i + 3){

            for(int j = 0; j < 9; j = j + 3){

                Set<Character> matrixSet = new HashSet<Character>();

                for(int m = i; m < i + 3; m++){

                    for(int n = j; n < j + 3; n++){

                        if(board[m][n] != '.'){

                            if(matrixSet.contains(board[m][n])){

                                return false;

                            }else{

                                matrixSet.add(board[m][n]);

                            }

                        }

                    }

                }

            }

        }

        return true;

    }

}

这个解法,虽然第二个是四重循环,但是可以看到外面两层都是常数循环次数的,也就是3。而且每个元素也都被遍历了一次而已。所以其实时间复杂度只有O(n^2),n为棋盘的长或宽。

你可能感兴趣的:(sudo)