码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_Valid Sudoku

时间:2015-07-01 10:04:36      阅读:132      评论:0      收藏:0      [点我收藏+]

标签: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;
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode_Valid Sudoku

标签:valid sudoku

原文地址:http://blog.csdn.net/mnmlist/article/details/46706229

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!