您的位置:首页 > 编程语言 > Go语言

【Leetcode Algorithm】Valid Sudoku

2015-07-03 10:20 495 查看
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.



public class Solution {
public boolean isValidSudoku(char[][] board) {
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
//判断每行是否有相同元素出现
for(int i=0;i<9;i++){
for(int m=0;m<9;m++){
map.put((char)('1'+m),0);
}
for(int j=0;j<9;j++){
if('1'<=board[i][j]&&board[i][j]<='9'){
int value = map.get(board[i][j])+1;
map.put(board[i][j], value);
if(map.get(board[i][j])>1){
return false;
}
}
}
}
//判断每列是否有相同元素出现
for(int i=0;i<9;i++){
for(int m=0;m<9;m++){
map.put((char)('1'+m),0);
}
for(int j=0;j<9;j++){
if('1'<=board[j][i]&&board[j][i]<='9'){
int value = map.get(board[j][i])+1;
map.put(board[j][i], value);
if(map.get(board[j][i])>1){
return false;
}
}
}
}
//判断每一个子格里(sub-boxes of the grid)是否有相同元素
for(int i=0;i<9;i=i+3){
for(int j=0;j<9;j=j+3){
for(int m=0;m<9;m++){
map.put((char)('1'+m),0);
}
for(int k=0;k<3;k++){
for(int x=0;x<3;x++){
if('1'<=board[i+k][j+x]&&board[i+k][j+x]<='9'){
int value = map.get(board[i+k][j+x])+1;
map.put(board[i+k][j+x], value);
if(map.get(board[i+k][j+x])>1){
return false;
}
}
}
}
}
}
return true;
}
}

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode algorithm