首页 > 代码库 > 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
‘.‘
.
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.
方法
只需要判断每一行,每一列以及每一个小矩形里面没有重复的元素即可。如果是空着的,默认为正确的。private boolean isValidRow(char[][] board) { int len = 9; boolean[] status = new boolean[len]; for (int i = 0; i < len; i++) { for (int k = 0; k < len; k++) { status[k] = false; } for (int j = 0; j < len; j++) { if (board[i][j] != '.') { if (status[board[i][j] - '1']) { return false; } else { status[board[i][j] - '1'] = true; } } } } return true; } private boolean isValidColumn(char[][] board) { int len = 9; boolean[] status = new boolean[len]; for (int i = 0; i < len; i++) { for (int k = 0; k < len; k++) { status[k] = false; } for (int j = 0; j < len; j++) { if (board[j][i] != '.') { if (status[board[j][i] - '1']) { return false; } else { status[board[j][i] - '1'] = true; } } } } return true; } private boolean isValidBoxes(char[][] board) { int len = 9; boolean[] status = new boolean[len]; for (int i = 0; i < len; i = i + 3) { for (int j = 0; j < len; j = j + 3) { for (int k = 0; k < len; k++) { status[k] = false; } for (int p = 0; p < 3; p++) { for (int q = 0; q < 3; q++) { if (board[i + p][j + q] != '.') { if (status[board[i + p][j + q] - '1']) { return false; } else { status[board[i + p][j + q] - '1'] = true; } } } } } } return true; } public boolean isValidSudoku(char[][] board) { return isValidRow(board) && isValidColumn(board) && isValidBoxes(board); }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。