leetcode - 36.Valid Sudoku
2017-03-04 10:04
507 查看
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.
Solution1:
public boolean isValidSudoku(char[][] board) { // - for (char[] chars : board) { Set<Character> set = new HashSet<>(); for (char c : chars) { if (!canAdd(set, c)) { return false; } } } // | int i = 0; while (i < 9) { Set<Character> set = new HashSet<>(); for (char[] chars : board) { char c = chars[i]; if (!canAdd(set, c)) { return false; } } i++; } // --- // | | // --- return isValid(board, 0, 1, 2, 0, 1, 2) && isValid(board, 3, 4, 5, 0, 1, 2) && isValid(board, 6, 7, 8, 0, 1, 2) // && isValid(board, 0, 1, 2, 3, 4, 5) && isValid(board, 3, 4, 5, 3, 4, 5) && isValid(board, 6, 7, 8, 3, 4, 5) // && isValid(board, 0, 1, 2, 6, 7, 8) && isValid(board, 3, 4, 5, 6, 7, 8) && isValid(board, 6, 7, 8, 6, 7, 8); } private boolean isValid(char[][] board, int x1, int x2, int x3, int y1, int y2, int y3) { Set<Character> set = new HashSet<>(); return canAdd(set, board[x1][y1]) && canAdd(set, board[x2][y1]) && canAdd(set, board[x3][y1]) // && canAdd(set, board[x1][y2]) && canAdd(set, board[x2][y2]) && canAdd(set, board[x3][y2]) // && canAdd(set, board[x1][y3]) && canAdd(set, board[x2][y3]) && canAdd(set, board[x3][y3]); } private boolean canAdd(Set<Character> set, char c) { if (c == '.' || set.add(c)) { return true; } return false; }
Solution2:
better
public boolean isValidSudoku1(char[][] board) { for(int i = 0; i < 9; i++){ HashSet<Character> row = new HashSet<>(); HashSet<Character> column = new HashSet<>(); HashSet<Character> cube = new HashSet<>(); for(int j = 0; j < 9; j++){ if(board[i][j] != '.' && !row.add(board[i][j])){ return false; } if(board[j][i] != '.' && !column.add(board[j][i])){ return false; } int rowIndex = (i / 3) * 3 + j / 3; int columnIndex = (i % 3) * 3 + j % 3; if(board[rowIndex][columnIndex] != '.' && !cube.add(board[rowIndex][columnIndex])){ return false; } } } return true; }
相关文章推荐
- Leetcode 36 Valid Sudoku 数独的合法性判断
- [leetcode 36] Valid Sudoku
- leetcode-36 Valid Sudoku
- [leetcode]36题 Valid Sudoku的JavaScript解法
- leetcode-36 Valid Sudoku
- LeetCode36——Valid Sudoku
- leetcode 36. Valid Sudoku
- LeetCode-36-Valid Sudoku(模拟/遍历)-Easy
- leetcode 36. Valid Sudoku
- leetcode 36 Valid Sudoku
- python实现 LeetCode36——Valid Sudoku
- LeetCode 36 Valid Sudoku(有效数独)
- LeetCode 36 Valid Sudoku (C,C++,Java,Python)
- leetcode 36. Valid Sudoku
- LeetCode(36)Valid Sudoku
- 【LeetCode】36. Valid Sudoku
- [LeetCode] 36. Valid Sudoku
- LeetCode - 36. Valid Sudoku
- LeetCode 36 Valid Sudoku
- Java [leetcode 36]Valid Sudoku