LeetCode Valid Sudoku

54 篇文章 0 订阅
3 篇文章 0 订阅

 原题链接在这里:https://leetcode.com/problems/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.

Hide Tags
  Hash Table
Hide Similar Problems
  (H) Sudoku Solver









这道题基本没有什么快速方法,唯一就是brute force.

首先在检查前,给出的board是否符合基本要求,是否为空。

然后检查每一行每一列,但问题的关键是如何检查sub box. 这里设值index 0-8 box, loop row with box/3*3 - box/3*3+3, loop column with box%3*3 - box%3*3+3.

这个小trick要记住。

这里选用HashSet 作为检验是否有重复的data structure, 但切记:在outer loop 开始时 要clear HashSet.


AC Java

public class Solution {
    public boolean isValidSudoku(char[][] board) {
        if(board == null || board.length != 9 || board[0].length != 9){
            return false;
        }
        
        HashSet hs = new HashSet();
        
        //Check each rows
        for(int i = 0;i<board.length;i++){
            hs.clear();
            for(int j = 0; j<board[0].length; j++){
                if(board[i][j] != '.'){
                    if(!hs.contains(board[i][j])){
                        hs.add(board[i][j]);
                    }
                    else{
                        return false;
                    }
                }
            }
        }
        
        //check each column
        for(int j = 0;j<board[0].length;j++){
            hs.clear();
            for(int i = 0; i<board.length; i++){
                if(board[i][j] != '.'){
                    if(!hs.contains(board[i][j])){
                        hs.add(board[i][j]);
                    }
                    else{
                        return false;
                    }
                }
            }
        }
        
        //check each subBox
        for(int box = 0;box<9;box++){
            hs.clear();
            for(int i = box/3*3; i<box/3*3+3; i++)
                for(int j = box%3*3;j<box%3*3+3;j++){
                   if(board[i][j] != '.'){
                    if(!hs.contains(board[i][j])){
                        hs.add(board[i][j]);
                    }
                    else{
                        return false;
                    }
                } 
                }
        }
        
        return true;
        
    }
}

可以看到,time complexity = O(n^2).





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值