Valid Sudoku,validsudoku
本文是在學習中的總結,歡迎轉載但請註明出處:http://blog.csdn.net/pistolove/article/details/42528601
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.
思路:
(1)題意為判斷一個數獨是否有效。
(2)題意不是讓我們求解出整個數獨(當然,如果真的求解還是很複雜的),而是判斷數獨中已有資料是否有效。
(3)本文的思路還是暴力破解,因為沒有想到其它好的方法。對數獨對應的9*9的二維數組進行遍曆,對於任意一個不為'.'的數字,都需要對其所在的行、列、以及3*3的塊地區進行判斷,如果有重複出現的情況,那麼數獨就是無效的,具體見下方代碼。
(4)希望本文對你有所協助。
演算法代碼實現如下:
public boolean isValidSudoku(char[][] board) {for (int i = 0; i < board.length; i++) {for (int j = 0; j < board[i].length; j++) {char curr = board[i][j];if(curr=='.'){continue;}//行for (int k = j+1; k < board.length; k++) {if(curr==board[i][k]){return false;}}//列for (int k = i+1; k < board.length; k++) {if(curr==board[k][j]){return false;}}//3*3 方塊if(i>=0&&i<3&&j>=0&&j<3){int count=0;for (int k1 = 0; k1 < 3; k1++) {for (int k2 = 0; k2 < 3; k2++) {if(board[k1][k2]==curr){count++;}if(count>1) return false;}}}if(i>=0&&i<3&&j>=3&&j<6){int count=0;for (int k1 = 0; k1 < 3; k1++) {for (int k2 = 3; k2 < 6; k2++) {if(board[k1][k2]==curr){count++;}if(count>1) return false;}}}if(i>=0&&i<3&&j>=6&&j<9){int count=0;for (int k1 = 0; k1 < 3; k1++) {for (int k2 = 6; k2 < 9; k2++) {if(board[k1][k2]==curr){count++;}if(count>1) return false;}}}if(i>=3&&i<6&&j>=0&&j<3){int count=0;for (int k1 = 3; k1 < 6; k1++) {for (int k2 = 0; k2 < 3; k2++) {if(board[k1][k2]==curr){count++;}if(count>1) return false;}}}if(i>=3&&i<6&&j>=3&&j<6){int count=0;for (int k1 = 3; k1 < 6; k1++) {for (int k2 = 3; k2 < 6; k2++) {if(board[k1][k2]==curr){count++;}if(count>1) return false;}}}if(i>=3&&i<6&&j>=6&&j<9){int count=0;for (int k1 = 3; k1 < 6; k1++) {for (int k2 = 6; k2 < 9; k2++) {if(board[k1][k2]==curr){count++;}if(count>1) return false;}}}if(i>=6&&i<9&&j>=0&&j<3){int count=0;for (int k1 = 6; k1 < 9; k1++) {for (int k2 = 0; k2 < 3; k2++) {if(board[k1][k2]==curr){count++;}if(count>1) return false;}}}if(i>=6&&i<9&&j>=3&&j<6){int count=0;for (int k1 = 6; k1 < 9; k1++) {for (int k2 = 3; k2 < 6; k2++) {if(board[k1][k2]==curr){count++;}if(count>1) return false;}}}if(i>=6&&i<9&&j>=6&&j<9){int count=0;for (int k1 = 6; k1 < 9; k1++) {for (int k2 = 6; k2 < 9; k2++) {if(board[k1][k2]==curr){count++;}if(count>1) return false;}}}}}return true;}