Leetcode:36. Valid Sudoku(JAVA)

来源:互联网 发布:pr导出淘宝视频 编辑:程序博客网 时间:2024/05/23 19:24

【问题描述】

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.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems

【思路】

使用HashSet依次按行、列、小格检查。

【code】

public class Solution {    public boolean isValidSudoku(char[][] board) { Set<Character> set = new HashSet<Character>();// rowfor (int i = 0; i < 9; i++) {for (int j = 0; j < 9; j++) {if (board[i][j] == '.') {continue;}if (set.contains(board[i][j])) {return false;}set.add(board[i][j]);}set.clear();}// columnfor (int i = 0; i < 9; i++) {for (int j = 0; j < 9; j++) {if (board[j][i] == '.') {continue;}if (set.contains(board[j][i])) {return false;}set.add(board[j][i]);}set.clear();}// sub-gridfor (int i = 0; i < 9; i++) {for (int j = i / 3 * 3; j < i / 3 * 3 + 3; j++) {for (int k = (i % 3) * 3; k < (i % 3) * 3 + 3; k++) {if (board[j][k] == '.') {continue;}if (set.contains(board[j][k])) {return false;}set.add(board[j][k]);}}set.clear();}return true;    }}


0 0
原创粉丝点击