LeetCode.36 Valid Sudoku

来源:互联网 发布:移动蜂窝数据是什么 编辑:程序博客网 时间:2024/06/05 07:14

题目:

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.

提示:

题目说明不需要完全填满,只需要判断所填数字是否满足数独条件(对应的数字行和列中不存在与该数字相同的,而且该数字所在的子宫3*3中也不存在相同的数字),即返回true;否则表示为无效的数独。

分析:

public class Solution {    public boolean isValidSudoku(char[][] board) {        //满足每一行、每一列、每一个粗线宫(3*3)内的数字均含1-9        boolean flag=true;        for(int i=0;i<9;i++){            for(int j=0;j<9;j++){                //跳过'.'                if(board[i][j]=='.'){                    continue;                }else{                    //是数字,就进行比较                //比较宫内                for(int m=(i/3)*3;m<(i/3)*3+3;m++){//根据除数判断宫                        for(int n=(j/3)*3;n<(j/3)*3+3;n++){                        if(m==i||n==j)continue;//同行同列不比                        else if(board[m][n]=='.')continue;                            else{                                 if(board[i][j]==board[m][n])return false;                             }                        }                    }                                    //比较row                    for(int m=j+1;m<9;m++){                        if(board[i][m]=='.')continue;                        else{                            if(board[i][j]==board[i][m])return false;                        }                    }                    //比较col                    for(int n=i+1;n<9;n++){                        if(board[n][j]=='.')continue;                        else{                            if(board[i][j]==board[n][j])return false;                        }                    }                }            }        }        return flag;            }}

原创粉丝点击