36. Valid Sudoku

来源:互联网 发布:c语言product函数 编辑:程序博客网 时间:2024/06/09 20:17

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


思路: 即判断每行每列和9个正方形中有没有出现重复的数字,若出现则返回false.

时间复杂度:O(N^2)

空间复杂度: O(1)

<span style="font-size:14px;">public boolean isValidSudoku(char[][] board) {        int[] flag=new int[9];        int i,j;                //judge each row        for(i=0;i<9;i++){            flag=new int[9];            for(j=0;j<9;j++){                if(board[i][j]!='.'){                    if(flag[board[i][j]-'1']==1)                        return false;                    else                        flag[board[i][j]-'1']=1;                }            }        }                //judge each column        for(i=0;i<9;i++){            flag=new int[9];            for(j=0;j<9;j++){                if(board[j][i]!='.'){                    if(flag[board[j][i]-'1']==1)                        return false;                    else                        flag[board[j][i]-'1']=1;                }            }        }                //judge each small square        int row,column;        for(i=0;i<9;i++){            flag=new int[9];            row=(i/3)*3;            column=(i%3)*3;            for(j=0;j<9;j++){                if(board[row+j/3][column+j%3]!='.'){                    if(flag[board[row+j/3][column+j%3]-'1']==1)                        return false;                    else                        flag[board[row+j/3][column+j%3]-'1']=1;                }            }        }                return true;    }</span>


0 0
原创粉丝点击