您的位置:首页 > 其它

36 Valid Sudoku

2015-08-19 15:31 225 查看
/*

* 需要判断

* (1)每一行

* (2)每一列

* (3)九个子正方形

* 是否都满足没有重复的数字

* 测试矩阵:

* char[][] board = {

{'5','3','.','.','7','.','.','.','.'},

{'6','.','.','1','9','5','.','.','.'},

{'.','9','8','.','.','.','.','6','.'},

{'8','.','.','.','6','.','.','.','3'},

{'4','.','.','8','.','3','.','.','1'},

{'7','.','.','.','2','.','.','.','6'},

{'.','6','.','.','.','.','2','8','.'},

{'.','.','.','4','1','9','.','.','5'},

{'.','.','.','.','8','.','.','7','9'}

};

*/

public class Solution {

public boolean isValidSudoku(char[][] board) {

if(board==null) return false;

int cols = board[0].length;

int rows = board.length;

for(int i=0;i<rows;++i){

if(!judgeRow(board, i)) return false;

}

for(int j=0;j<cols;++j){

if(!judgeCol(board, j)) return false;

}

for(int i=0;i<rows;i+=3){

for(int j=0;j<cols;j+=3){

if(!judgeRec(board,i,j)) return false;

}

}

return true;

}

public boolean judgeRow(char[][] board, int row){

int[] vis = new int[10];

Arrays.fill(vis, 0);

int cols = board[row].length;

for(int j=0;j<cols;++j){

if(board[row][j]=='.'){

continue;

}

int tmp = new Integer(board[row][j] - '0');

if(vis[tmp]==0){

vis[tmp] = 1;

}else{

return false;

}

}

return true;

}

public boolean judgeCol(char[][] board, int col){

int[] vis = new int[10];

Arrays.fill(vis, 0);

int rows = board.length;

for(int i=0;i<rows;++i){

if(board[i][col]=='.'){

continue;

}

int tmp = new Integer(board[i][col] - '0');

if(vis[tmp]==0){

vis[tmp] = 1;

}else{

return false;

}

}

return true;

}

public boolean judgeRec(char[][] board, int row, int col){

int[] vis = new int[10];

Arrays.fill(vis, 0);

for(int i=row;i<row+3;++i){

for(int j=col;j<col+3;++j){

if(board[i][j]=='.') continue;

int tmp = new Integer(board[i][j] - '0');

if(vis[tmp]==0){

vis[tmp] = 1;

}else{

return false;

}

}

}

return true;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: