[leetcode]36. Valid Sudoku@Java解题报告

来源:互联网 发布:班服制作软件 编辑:程序博客网 时间:2024/06/05 09:40

https://leetcode.com/problems/valid-sudoku/description/


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.



package go.jacob.day802;import java.util.HashSet;import java.util.Set;/** * 36. Valid Sudoku *  * @author Jacob * */public class Demo1 {/* * 题意:让你判断这是否是一个正确的数独, * 即确定每一行,每一列以及每一个九宫格是否有相同的数字 * HashSet的add方法,当添加成功(即set中不含有该元素)返回true */public boolean isValidSudoku(char[][] board) {// 每一个大循环确定一行,一列,一个九宫格for (int i = 0; i < 9; i++) {Set<Character> row = new HashSet<Character>();Set<Character> col = new HashSet<Character>();Set<Character> cube = new HashSet<Character>();for (int j = 0; j < 9; j++) {// 第i行if (board[i][j] != '.' && !row.add(board[i][j]))return false;// 第i列if (board[j][i] != '.' && !col.add(board[j][i]))return false;//int cubeRow = 3 * (i / 3) + j / 3, cubeCol = 3 * (i % 3) + j % 3;if (board[cubeRow][cubeCol] != '.' && !cube.add(board[cubeRow][cubeCol]))return false;}}return true;}}


原创粉丝点击