您的位置:首页 > 其它

LeetCode Valid Sudoku

2015-07-21 23:45 295 查看
原题链接在这里:https://leetcode.com/problems/valid-sudoku/

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.

Hide Tags

Hash Table

Hide Similar Problems

(H) Sudoku Solver

这道题基本没有什么快速方法,唯一就是brute force.

先一行一行检查

然后一列一列检查,这里注意外层for loop是j

最后一个一个小方块来检查,关键是如何检查sub box. 这里设值index 0-8 box, loop row with box/3*3 - box/3*3+3, loop column with box%3*3 - box%3*3+3.

Time Complexity: O(n^2). Space: O(1).

AC Java:

public class Solution {
public boolean isValidSudoku(char[][] board) {
if(board == null || board.length != 9 || board[0].length != 9){
return false;
}

HashSet<Character> hs = new HashSet<Character>();
//check each row
for(int i = 0; i<board.length; i++){
hs.clear();
for(int j = 0; j<board[0].length; j++){
if(board[i][j] != '.'){
if(!hs.contains(board[i][j])){
hs.add(board[i][j]);
}else{
return false;
}
}
}
}

//check each column
for(int j = 0; j<board[0].length; j++){
hs.clear();
for(int i = 0; i<board.length; i++){
if(board[i][j] != '.'){
if(!hs.contains(board[i][j])){
hs.add(board[i][j]);
}else{
return false;
}
}
}
}

//check each subbox
for(int box = 0; box<9; box++){
hs.clear();
for(int i = box/3*3; i<box/3*3+3; i++){
for(int j = box%3*3; j<box%3*3+3; j++){
if(board[i][j] != '.'){
if(!hs.contains(board[i][j])){
hs.add(board[i][j]);
}else{
return false;
}
}
}
}
}
return true;
}
}


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