首页 > 代码库 > [leetcode] Valid Sudoku
[leetcode] 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.
https://oj.leetcode.com/problems/valid-sudoku/
思路:按照规则,先检查行,然后检查列,然后检查9格。
public class Solution { public boolean isValidSudoku(char[][] board) { int i; for (i = 0; i < 9; i++) { if (!isValid(board, i, i + 1, 0, 9)) return false; } int j; for (j = 0; j < 9; j++) { if (!isValid(board, 0, 9, j, j + 1)) return false; } for (i = 0; i < 9; i = i + 3) for (j = 0; j < 9; j = j + 3) { if (!isValid(board, i, i + 3, j, j + 3)) return false; } return true; } private boolean isValid(char[][] board, int iBegin, int iEnd, int jBegin, int jEnd) { HashSet<Character> set = new HashSet<Character>(); for (int i = iBegin; i < iEnd; i++) for (int j = jBegin; j < jEnd; j++) { if (set.contains(board[i][j])) return false; else if (board[i][j] != ‘.‘) set.add(board[i][j]); } return true; } public static void main(String[] args) { char[][] board = { { ‘5‘, ‘3‘, ‘.‘, ‘.‘, ‘7‘, ‘.‘, ‘.‘, ‘.‘, ‘.‘ }, { ‘6‘, ‘.‘, ‘.‘, ‘1‘, ‘9‘, ‘5‘, ‘.‘, ‘.‘, ‘.‘ }, { ‘.‘, ‘9‘, ‘8‘, ‘.‘, ‘.‘, ‘.‘, ‘.‘, ‘6‘, ‘.‘ }, { ‘8‘, ‘.‘, ‘.‘, ‘.‘, ‘6‘, ‘.‘, ‘.‘, ‘.‘, ‘3‘ }, { ‘4‘, ‘.‘, ‘.‘, ‘8‘, ‘.‘, ‘3‘, ‘.‘, ‘.‘, ‘1‘ }, { ‘7‘, ‘.‘, ‘.‘, ‘.‘, ‘2‘, ‘.‘, ‘.‘, ‘.‘, ‘6‘ }, { ‘.‘, ‘6‘, ‘.‘, ‘.‘, ‘.‘, ‘.‘, ‘2‘, ‘8‘, ‘.‘ }, { ‘.‘, ‘.‘, ‘.‘, ‘4‘, ‘1‘, ‘9‘, ‘.‘, ‘.‘, ‘5‘ }, { ‘.‘, ‘.‘, ‘.‘, ‘.‘, ‘8‘, ‘.‘, ‘.‘, ‘7‘, ‘9‘ } }; System.out.println(new Solution().isValidSudoku(board)); }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。