Valid Sudoku

 Total Accepted: 33785 Total Submissions: 123877My Submissions

Question Solution 


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 '.'.

Leetcode#36Valid Sudoku_partially

A partially filled sudoku which is valid.



分析:每行中每个元素可以为空,但0~9数字只出现只能出现一次;

      每列中每个元素可以为空,但0~9数字只出现只能出现一次;

      每个小九宫格中每个元素可以为空,但0~9数字只出现只能出现一次;


public class Solution {

    boolean isV(int xs, int xe, int ys, int ye, char[][] board)

    {

            Map<Character,Integer> z=new HashMap<Character,Integer>();

            for(int i=xs;i<=xe;i++)

                for(int j=ys;j<=ye;j++)

                    if(board[i][j]>='0'&&board[i][j]<='9')

                        if(z.get(board[i][j])!=null)

                            return false;

                        else

                            z.put(board[i][j],1);

            return true;

    }

    

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

           Map<Character,Integer> x;

           Map<Character,Integer> y;

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

           {

               x=new HashMap<Character,Integer>();

               y=new HashMap<Character,Integer>();

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

                {

                    if(board[i][j]>='0'&&board[i][j]<='9')

                        if(x.get(board[i][j])!=null)

                            return false;

                        else

                            x.put(board[i][j],1);

                    if(board[j][i]>='0'&&board[j][i]<='9')

                        if(y.get(board[j][i])!=null)

                            return false;

                        else

                            y.put(board[j][i],1);

                }

                x.clear();

                y.clear();

           }

         

         if(isV(0,2,0,2,board)&&isV(3,5,0,2,board)&&isV(6,8,0,2,board)&&isV(0,2,3,5,board)&&isV(3,5,3,5,board)&&isV(6,8,3,5,board)&&isV(0,2,6,8,board)&&isV(3,5,6,8,board)&&isV(6,8,6,8,board))

            return true;

        else

            return false;

    }

}