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

思路:

和一圈又一圈由外而内打印数字一样。考察的也就是程序的运行流程和边界值的把握。而这一题就更简单。由题意可知,本题考查的是每行每列和9个板块之间是不是都符合要求,和八皇后有点像。但要简单的多。

代码:

public class Solution {
    public boolean isValidSudoku(char[][] board) {
        BitSet set=new BitSet();
        int i,j,m,k,index_i,index_j;
        int num=0;
        //to evaluate if the 9 blocks are OK
        for( i=0;i<board.length;i+=3)
        {
            for( j=0;j<board[0].length;j+=3)
            {
                set.clear();
                index_i=i+3;
                index_j=j+3;
                for( m=i;m<index_i;m++)
                {
                    for( k=j;k<index_j;k++)
                    {
                        if(board[m][k]!='.')
                        {
                            num=board[m][k]-'0';
                            if(!set.get(num))
                                set.set(num);
                            else
                                return false;
                        }
                    }
                }
            }
        }
        //to evaluate the rows
        for(i=0;i<board.length;i++)
        {
            set.clear();
            for(j=0;j<board[0].length;j++)
            {
                if(board[i][j]!='.')
                {
                    num=board[i][j]-'0';
                     if(!set.get(num))
                        set.set(num);
                    else
                        return false;
                }
                
            }
        }
        //to evalueate the colums
        for(j=0;j<board[0].length;j++)
        {
            set.clear();
            for( i=0;i<board.length;i++)
            {
                if(board[i][j]!='.')
                {
                    num=board[i][j]-'0';
                    if(!set.get(num))
                     set.set(num);
                    else
                     return false;
                }
            }
        }
        return true;
    }
}


posted on 2017-08-04 13:15  wgwyanfs  阅读(77)  评论(0编辑  收藏  举报

导航