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.
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package leetcode; | |
import java.util.ArrayList; | |
/** | |
* Solution: Don't need to care anything but that three Sodoku rules. | |
* 1. Each row must have the number 1-9 occuring just once. | |
* 2. Each column ..... | |
* 3. The number 1-9 must occur just once in each of sub-boxes of the grid. | |
* Althought I think there's something I need to care, something I may miss. But that's the result. | |
* I refactor sub-box check to avoid another nest-loop. | |
* | |
* Reference: http://www.cnblogs.com/zhaolizhen/p/Sudoku.html | |
* @author jeffwan | |
* @date Apr 3, 2014 | |
*/ | |
public class IsValidSudoku { | |
public boolean isValidSudoku(char[][] board) { | |
if (board == null || board.length == 0 || board[0].length == 0) { | |
return false; | |
} | |
int length = board.length; | |
ArrayList<Integer> visited = new ArrayList<Integer>(); | |
// Check every row | |
for (int i = 0; i < length; i++) { | |
visited.clear(); | |
for (int j = 0; j < length; j++) { | |
if (!process(visited, board[i][j])) { | |
return false; | |
} | |
} | |
} | |
// Check every colum | |
for (int i = 0; i < length; i++) { | |
visited.clear(); | |
for (int j = 0; j < length; j++) { | |
if (!process(visited, board[j][i])) { | |
return false; | |
} | |
} | |
} | |
// Check every subx-box | |
for (int i = 0; i < length; i += 3) { | |
for (int j = 0; j < length; j += 3) { | |
visited.clear(); | |
for (int k = 0; k < length; k++) { | |
if (!process(visited, board[i + k / 3][j + k % 3])) { | |
return false; | |
} | |
} | |
} | |
} | |
return true; | |
} | |
private boolean process(ArrayList<Integer> visited, char digit) { | |
if (digit == '.') { | |
return true; | |
} | |
int num = Character.getNumericValue(digit); | |
if (num < 1 || num > 9 || visited.contains(num)) { | |
return false; | |
} | |
visited.add(num); | |
return true; | |
} | |
} |
No comments:
Post a Comment