zoukankan      html  css  js  c++  java
  • 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 {
        
        //判断一行或一列或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;
        }
    }
  • 相关阅读:
    使用react+html2canvas+jspdf实现生成pdf文件
    命名函数表达式
    java-信息安全(二十)国密算法 SM1,SM2,SM3,SM4
    003-docker-单宿主机下的网络模式
    【性能扫盲】性能测试面试题
    LoadRunner函数
    爬取干货集中营的美女图片
    ELK 性能优化实践 ---总结篇
    ELK 性能优化实践
    告警图片-搞笑的
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4268049.html
Copyright © 2011-2022 走看看