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

Valid Sudoku

时间:2015-02-02 17:39:12      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

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 {
    
    //判断一行或一列或9宫格里的9个数是否有重复
    public boolean isValidRow(char[] row){
        String str = "";
        for(int i=0;i<9;i++){
            if(row[i]!=‘.‘){
                if(!str.contains(String.valueOf(row[i]))){
                    str+=row[i];
                }
                else{
                    return false;
                }
            }
        }
        return true;
    }
    
    //判断每行是否有重复数字
    public boolean isValidLine(char[][] board){
        for(int i=0;i<9;i++){
            if(isValidRow(board[i])==false){
                return false;
            }
        }
        return true;
    }
    //判断每列是否有重复数字
    public boolean isValidColumn(char[][] board){
        for(int i = 0;i < 9;i++){
            char[] str = new char[9]; 
            for(int j = 0;j <9;j++){
                str[j] = board[j][i];
            }
            if(isValidRow(str)==false){
                return false;
            }
        }
        return true;
    }
    //判断每个九宫格里是否有重复数字
    public boolean isValidSquare(char[][] board){
        for(int i=0;i<=6;i=i+3){
            int x = i;
            for(int j=0;j<=6;j=j+3){
                char[] str = new char[9]; 
                int y = j;
                for(int m=0;m<3;m++){
                    for(int n=0;n<3;n++){
                        str[m*3+n] = board[x+m][y+n];
                    }
                }
                if(isValidRow(str)==false){
                    return false;
                }
            }
        }
        return true;
    }
    
    public boolean isValidSudoku(char[][] board) {
        if(isValidLine(board)==false){
            return false;
        }
        if(isValidColumn(board)==false){
            return false;
        }
        if(isValidSquare(board)==false){
            return false;
        }
        return true;
    }
}

 

Valid Sudoku

标签:

原文地址:http://www.cnblogs.com/mrpod2g/p/4268049.html

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