36. Valid Sudoku

来源:互联网 发布:江大教务网络管理系统 编辑:程序博客网 时间:2024/06/06 09:44

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 '.'.


判断给定的数组是不是合法的数独,

先判断行、列,再判断小框,注意索引值的处理,i+3 j+3  i+k/3,i+k%3

用一个方法来判断数值是否合法,


public class Solution {      boolean []bool=new boolean[9];    public boolean isValidSudoku(char[][] board) {        for(int i=0;i<9;i++){            Arrays.fill(bool,false);            for(int j=0;j<9;j++){                if(!process(bool,board[i][j]))                    return false;            }        }        for(int i=0;i<9;i++){            Arrays.fill(bool,false);            for(int j=0;j<9;j++){                 if(!process(bool,board[j][i]))                    return false;            }        }        for(int i=0;i<9;i+=3){            for(int j=0;j<9;j+=3){                Arrays.fill(bool,false);                for(int k=0;k<9;k++){                    if(!process(bool,board[i+k/3][j+k%3]))                        return false;                }            }        }        return true;    }    public boolean process(boolean[]bool,char ch){        if(ch=='.') return true;        // int num=ch-'0';        if(ch-'0'<1||ch-'0'>9||bool[ch-'0'-1])            return false;         bool[ch-'0'-1] =true;         return true;               }}


0 0
原创粉丝点击