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.

Note:

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

题目:给一个数独表,判断现在是否符合数独的要求。行、列、粗线9宫格都包含1~9。即没有重复的数字。

思路:最简单的就是行、列、9宫格单独判断。

public boolean isValidSudoku(char[][] board) {
        for(int i = 0; i < 9;i++) {
			int[] num = new int[9];
			int[] num1 = new int[9];
			for(int j = 0; j < 9;j++) {//判断列
				
				if(board[i][j] != '.') {
					num[j]  = board[i][j] -'0';
				}
			}
			if(!isValid(num)) {
				return false;
			}
			
			for(int k = 0; k < 9;k++) {//判断行
				if(board[k][i] != '.') {
					num1[k]  = board[k][i] -'0';
				}
			}
			if(!isValid(num1)) {
				return false;
			}
		}
		
		for(int i = 0; i < 9;i = i+3) {//判断9宫格
			for(int y = 0; y < 9;y = y + 3) {
				List<Integer> list = new ArrayList<Integer>();
				for(int x = i;x < i+3 ;x++) {
					for(int z = y;z < y+3;z++) {
						if(board[x][z] != '.') {
							if(!list.contains(board[x][z] - '0'))
								list.add(board[x][z] - '0');
							else {
								return false;
							}
						}
					}
				}
			}
			
		}
		return true;
    }
    public boolean isValid(int[] num) {
		Map<Integer, Integer> map = new HashMap<Integer, Integer>();
		List<Integer> list = new ArrayList<Integer>();
		for(int i = 0; i < num.length;i++) {
			if(num[i] != 0 && list.contains(num[i])) {
				return false;
			} else {
				list.add(num[i]);
			}
		} 
		return true;
	}

种一棵树最好的时间是十年前,其次是现在!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值