標籤:lintcode file character empty HERE param follow font png
Description
Determine whether a Sudoku is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character ..
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
Clarification
What is Sudoku?
- http://sudoku.com.au/TheRules.aspx
- https://zh.wikipedia.org/wiki/數獨
- https://en.wikipedia.org/wiki/Sudoku
- http://baike.baidu.com/subview/961/10842669.htm
Example
The following partially filed sudoku is valid.
解題:判斷數獨是否有效。如果每一行、每一列、每一個小方塊裡的數不重複,就算有效。當然,前提必須是1~9之間。此題空白部分是用“ . ”表示的,要注意一下。具體做法為,檢查行、列、方塊,把這些數拿出來,放在一個一維數組中,判斷這個一維數組裡的數,滿不滿足相應的條件。代碼如下:
public class Solution { /** * @param board: the board * @return: whether the Sudoku is valid */ public boolean isValidSudoku(char[][] board) { // write your code here char[]temp = new char[9]; for(int i = 0; i < 9; i++){ //檢查行 for(int j = 0; j < 9; j++){ temp[j] = board[i][j]; } if(judge(temp) == false){ return false; } //檢查列 for(int j = 0; j < 9; j++){ temp[j] = board[j][i]; } if(judge(temp) == false){ return false; } } //小格子 for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ int b = 0; for(int k = 0 + i * 3; k < 3 + i * 3; k++){ for(int m = 0 + j * 3; m < 3 + j * 3; m++){ temp[b++] = board[k][m]; } } if(judge(temp) == false) return false; } } return true; } public boolean judge(char[]temp){ for(int i =0; i < 9; i++){ if(temp[i] > ‘9‘ || temp[i] < ‘1‘ ){ if(temp[i] != ‘.‘) return false; } } for(int i = 1; i < 9; i++){ for(int j = 0; j < i; j++){ if(temp[i] == temp[j] ){ if(temp[i] != ‘.‘) return false; } } } return true; }}
389. Valid Sudoku【LintCode java】