• 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;
        }
    }


  • 相关阅读:
    整数因子分解问题(递归分治法、动态规划)
    背包问题(动态规划 C/C++)
    划分问题(Java 动态规划)
    算法:Common Subsequence(动态规划 Java 最长子序列)
    算法:矩阵连乘(Java)动态规划
    Frogs‘ Neighborhood(POJ 1659 C/C++)
    算法:线性时间选择(C/C++)
    sort(hdu oj 1425)计数排序和快速排序
    快速排序(递归和分治)
    a^b(取模运算)
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/7284545.html
Copyright © 2020-2023  润新知