Leetcode 36. Valid Sudoku [medium][java]

在这里插入图片描述

Example
在这里插入图片描述

Solution 1: Brute Force
Time complexity:O(9^2), space complexity: O()

class Solution {
    public boolean isValidSudoku(char[][] board) {
        
        //check row
        for(int i = 0; i < 9; i++) {
            Set<Character> chars = new HashSet();
            for(int j = 0; j < 9; j++) {
                //System.out.print("("+i + "," + j + "):" +board[i][j] + "; ");
                if(board[i][j] != '.') {
                    if(chars.contains(board[i][j]))
                        return false;
                    else
                       chars.add(board[i][j]); 
                }
            }
            
        }
        
        //check column
        for(int i = 0; i < 9; i++) {
            Set<Character> chars = new HashSet();
            for(int j = 0; j < 9; j++) {
                if(board[j][i] != '.') {
                    if(chars.contains(board[j][i]))
                        return false;
                    else
                        chars.add(board[j][i]);
                } 
                    
            }
        }
        
        //check box
        for(int k = 0; k < 9; k++) {
            Set<Character> chars = new HashSet();
            for(int i = 0; i < 3; i++) {
                int row = (i + k*3) % 9;
                for(int j = 0; j < 3; j++) {
                    int col = (j + k/3*3) ;
                    if(board[row][col] != '.') {
                        if(chars.contains(board[row][col]))
                            return false;
                        else
                            chars.add(board[row][col]);
                    } 
                        
                }
            }
        }        
        return true;
        
    }
}

Solution 2: check row, column & box at the same time

class Solution {
    public boolean isValidSudoku(char[][] board) {
        for (int i = 0; i < 9; i++) {
			HashSet<Character> row = new HashSet<>();
			HashSet<Character> column = new HashSet<>();
			HashSet<Character> cube = new HashSet<>();
			for (int j = 0; j < 9; j++) {
				// 检查第i行,在横坐标位置
				if (board[i][j] != '.' && !row.add(board[i][j]))
					return false;
				// 检查第i列,在纵坐标位置
				if (board[j][i] != '.' && !column.add(board[j][i]))
					return false;
				// 行号+偏移量
				int RowIndex = 3 * (i / 3) + j / 3;
				// 列号+偏移量
				int ColIndex = 3 * (i % 3) + j % 3;
				//每个小九宫格,总共9个
				if (board[RowIndex][ColIndex] != '.' 
						&& !cube.add(board[RowIndex][ColIndex]))
					return false;
			}
		}
		return true;
    }
}

Reference
https://blog.csdn.net/mine_song/article/details/70207326

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值