【Leetcode】Valid Sudoku in JAVA

来源:互联网 发布:阿里巴巴上传宝贝软件 编辑:程序博客网 时间:2024/06/08 18:56

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.

解题思路很明确:

1.竖着每列确定没有重复

2.横着每行确定没有重复

3.每个3*3的sub没有重复

用到的collection:HashSet,里面有一个方法,add()。往set里加入一个元素,如果已经存在则不加入,返回false。

import java.util.HashSet;public class validSudoku {public boolean isValidSudoku(char[][] board) {        //first judge columnfor(int i=0;i<board[0].length;i++){HashSet<Character> column = new HashSet<Character>();for(int j=0;j<board.length;j++){if(board[i][j]!='.'&&!column.add(board[i][j]))return false;}}//then judge rowfor(int i=0;i<board.length;i++){HashSet<Character> row = new HashSet<Character>();for(int j=0;j<board[i].length;j++){if(board[i][j]!='.'&&!row.add(board[i][j]))return false;}}//check 3*3 for(int i=0;i<3;i++){for(int j=0;j<3;j++){HashSet<Character> sub = new HashSet<Character>();for(int m=i*3;m<i*3+3;m++){for(int n=j*3;n<j*3+3;n++){if(board[m][n]!='.'&&!sub.add(board[m][n]))return false;}}}}return true;    }}


0 0