【LeetCode】 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.

java code :

 

public class Solution {
    public boolean isValidSudoku(char[][] board) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
         HashSet<Character> hash = new HashSet<Character>();
		 if(board == null)
			 return true;
		 for(int i = 0; i < board.length; i++)
		 {
			 hash.clear();
			 for(int j = 0; j < board[0].length; j++)
			 {
				 if(board[i][j] == '.')
					 continue;
				 if(!(board[i][j] >= '1' && board[i][j] <= '9'))
					 return false;
				 if(hash.isEmpty() || !hash.contains(board[i][j]))
					 hash.add(board[i][j]);
				 else return false;
			 }
		 }
		 hash.clear();
		 for(int i = 0; i < board[0].length; i++)
		 {
			 hash.clear();
			 for(int j = 0; j < board.length; j++)
			 {
				 if(board[j][i] == '.')
					 continue;
				 if(!(board[j][i] >= '1' && board[j][i] <= '9'))
					 return false;
				 if(hash.isEmpty() || !hash.contains(board[j][i]))
					 hash.add(board[j][i]);
				 else return false;
			 }
		 }
		 hash.clear();
		 
		 for(int i = 0; i < 9; i += 3)
		 {
			 
			 for(int j = 0; j < 9; j += 3)
			 {
				 hash.clear();
				 for(int row = 0; row < 3; row++)
				 {
					 for(int col = 0; col < 3; col++)
					 {
						 if(board[i+row][j+col] == '.')
							 continue;
						 if(!(board[i+row][j+col] >= '1' && board[i+row][j+col] <= '9'))
							 return false;
						 if(hash.isEmpty() || !hash.contains(board[i+row][j+col]))
							 hash.add(board[i+row][j+col]);
						 else return false;
					 }
				 }
			 }
		 }
		 hash = null;
		 return true;
    }
}


 

 

posted on   you Richer  阅读(518)  评论(0编辑  收藏  举报
编辑推荐:
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
阅读排行:
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法
点击右上角即可分享
微信分享提示