【Leetcode】Valid Sudoku in JAVA

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 column
		for(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 row
		for(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;
    }
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值