Valid Sudoku
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 '.'
.
思路:
简单的数学运算
我的代码:
public class Solution { public boolean isValidSudoku(char[][] board) { if(board == null || board.length == 0 || board[0].length == 0) return true; int row = board.length; int col = board[0].length; for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { char c = board[i][j]; if(c == '.') continue; else { //test row for(int k = 0; k < j; k++) { if(board[i][k] == c) return false; } //test col for(int k = 0; k < i; k++) { if(board[k][j] == c) return false; } //test box int boxRow = i/3; int boxCol = j/3; for(int m = boxRow * 3; m < boxRow * 3 + 3; m++) { for(int n = boxCol * 3; n < boxCol * 3 + 3; n++) { if(board[m][n] == '.' || (m == i && n == j)) continue; else { if(board[m][n] == c) return false; } } } } } } return true; } }
他人代码:
public boolean isValidSudoku(char[][] board) { // Start typing your Java solution below // DO NOT write main() function for(int i=0; i<board.length; i++){ for(int j=0; j<board[0].length; j++){ if(board[i][j]=='.') continue; char tmp = board[i][j]; board[i][j] = 'C'; boolean tr = isValid(board, i, j, tmp); board[i][j] = tmp; if(tr == false) return tr; } } return true; } public boolean isValid(char[][] board, int x, int y, char tmp){ for(int i=0; i<9; i++){ if(board[x][i] == tmp || board[i][y] == tmp) return false; } int start_x = x/3; int start_y = y/3; for(int i=0; i<9; i++){ int cur_x = start_x*3 + i/3; int cur_y = start_y*3 + i%3; if(board[cur_x][cur_y] == tmp) return false; } return true; }
学习之处:
- 测试了好多次才过 不能忍 错误之处是 start = i/3 end = i/3 + 3 正确应该是 start = i/3 * 3 end = i/3 * 3 + 3 忘记 * 3 + 3了
- 他人的代码用9 一次访问一行或者一列或者一个box,代码简单易行
posted on 2015-03-10 09:48 zhouzhou0615 阅读(102) 评论(0) 编辑 收藏 举报