(Java)LeetCode-36. 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.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.



这道题我刚开始还以为要求解这个数独呢,吓坏了,后来发现只需要判断初始给的这个数独是不是合法就行了,没什么难度。

最难的地方就在于用一个四层循环取出这大数独中的九个子正方形,然后判断~代码如下:

package datastru;

public class Solution {

	public boolean isValidSudoku(char[][] board) {
		for(int i = 0; i < 9; i++){
			if(check(board[i])){
				continue;
			}else{
				return false;
			}
		}
		char[] ch = new char[9];
		for(int i = 0; i < 9; i++){
			for(int j = 0; j < 9; j++){
				ch[j] = board[j][i];
			}
			if(check(ch)){
				continue;
			}else{
				return false;
			}
		}
		int line = 0;
		int col = 0;
		for(int m = 0; m < 3; m++){
			int index = 0;	
			for(int n = 0; n < 3; n++){
				for(int i = 0; i < 3 ; i++){
					for(int j = 0; j < 3; j++){
						ch[index++] = board[i+line*3][j+col*3];
					}
				}
				col++;
				index = 0;
				if(check(ch)){
					continue;
				}else{
					return false;
				}
			}
			line++;
			col = 0;
		}
		return true;
    }
	
	private boolean check(char[] ch){
		boolean[] flags = new boolean[9];
		for(char c : ch){
			if(c !='.'){
				int num = Integer.parseInt(String.valueOf(c));
				if(flags[num-1] == false){
					flags[num-1] = true;
				}else{
					return false;
				}
			}
		}
		return true;
	}
	
	public static void main(String[] args){
		Solution sol = new Solution();
//		char[][] nums = {{'.','8','7','6','5','4','3','2','1'},["..5.....6","....14...",".........",".....92..","5....2...",".......3.","...54....","3.....42.","...27.6.."]
//						 {'2','.','.','.','.','.','.','.','.'},
//						 {'3','.','.','.','.','.','.','.','.'},
//						 {'4','.','.','.','.','.','.','.','.'},
//						 {'5','.','.','.','.','.','.','.','.'},
//						 {'6','.','.','.','.','.','.','.','.'},
//						 {'7','.','.','.','.','.','.','.','.'},
//						 {'8','.','.','.','.','.','.','.','.'},
//						 {'9','.','.','.','.','.','.','.','.'}};
		
		char[][] nums = {{'.','.','5','.','.','.','.','.','6'},
						 {'.','.','.','.','1','4','.','.','.'},
						 {'.','.','.','.','.','.','.','.','.'},
						 {'.','.','.','.','.','9','2','.','.'},
						 {'5','.','.','.','.','2','.','.','.'},
						 {'.','.','.','.','.','.','.','3','.'},
						 {'.','.','.','5','4','.','.','.','.'},
						 {'3','.','.','.','.','.','4','2','.'},
						 {'.','.','.','2','7','.','6','.','.'}};
		boolean result = sol.isValidSudoku(nums);
		System.out.println(result);

	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值