码迷,mamicode.com
首页 > 编程语言 > 详细

389. Valid Sudoku【LintCode java】

时间:2018-07-15 12:59:45      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:lintcode   file   character   empty   HERE   param   follow   font   png   

Description

Determine whether a Sudoku is valid.

The Sudoku board could be partially filled, where empty cells are filled with the character ..

A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

Example

The following partially filed sudoku is valid.

技术分享图片

 

解题:判断数独是否有效。如果每一行、每一列、每一个小方块里的数不重复,就算有效。当然,前提必须是1~9之间。此题空白部分是用“ . ”表示的,要注意一下。具体做法为,检查行、列、方块,把这些数拿出来,放在一个一维数组中,判断这个一维数组里的数,满不满足相应的条件。代码如下:

public class Solution {
    /**
     * @param board: the board
     * @return: whether the Sudoku is valid
     */
    public boolean isValidSudoku(char[][] board) {
        // write your code here
        char[]temp = new char[9];
        for(int i = 0; i < 9; i++){
            //检查行
            for(int j = 0; j < 9; j++){
                temp[j] = board[i][j];
            }
            if(judge(temp) == false){
                return false;
            }
            //检查列
            for(int j = 0; j < 9; j++){
                temp[j] = board[j][i];
            }
            if(judge(temp) == false){
                return false;
            }
        }
        //小格子
        for(int i = 0; i < 3; i++){
            for(int j = 0; j < 3; j++){
                int b = 0;
                for(int k = 0 + i * 3; k < 3 + i * 3; k++){
                    for(int m = 0 + j * 3; m < 3 + j * 3; m++){
                        temp[b++] = board[k][m];
                    }
                }
                if(judge(temp) == false)
                return false;
                
            }
        }
        return true;
    }
    public boolean judge(char[]temp){
        for(int i =0; i < 9; i++){
            if(temp[i] > ‘9‘ || temp[i] < ‘1‘ ){
                if(temp[i] != ‘.‘)
                   return false;
            }
        }
        for(int i = 1; i < 9; i++){
            for(int j = 0; j < i; j++){
                if(temp[i] == temp[j] ){
                    if(temp[i] != ‘.‘)
                        return false;
                }
            }
        }
        return true;
    }
}

 

389. Valid Sudoku【LintCode java】

标签:lintcode   file   character   empty   HERE   param   follow   font   png   

原文地址:https://www.cnblogs.com/phdeblog/p/9313231.html

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