0036_Valid Sudoku

本文介绍了一种通过检查已填充的数字是否违反数独规则来验证数独有效性的方法。文章详细展示了如何利用HashSet来判断行、列及子格内的数字是否重复。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

JAVA

方法一

  并不知道如何来判断是不是一个可用的数独,只能尝试一下判断已经填写的数字中是否有不满足数独规则的,分别判断行、列、子格。没想到竟然过了,就是效率不高,在3/4左右。。

public class Solution {
    static int MAXSIZE = 9;
    static int SUBBOXSIZE = 3;
    public boolean isValidSudoku(char[][] board) {
        if (board.length != MAXSIZE || board[0].length != MAXSIZE){
            return false;
        }

        for (int i = 0; i < MAXSIZE; ++i){
            if (!judgeRow(board,i)){
                return false;
            }
        }

        for (int i = 0; i < MAXSIZE; ++i){
            if (!judgeColumn(board,i)){
                return false;
            }
        }

        for (int i = 0; i < MAXSIZE; i += 3){
            for(int j = 0; j < MAXSIZE; j += 3){
                if (!judgeSubBox(board,i,j)){
                    return false;
                }
            }
        }
        return true;
    }
    public boolean judgeRow(char[][] board,int row){
        HashSet<Character> used = new HashSet<Character>();
        for(int i = 0; i < MAXSIZE; ++i){
            if(board[row][i] != '.' && used.contains(board[row][i])){
                return false;
            }else{
                used.add(board[row][i]);
            }
        }
        return true;
    }

    public boolean judgeColumn(char[][] board,int column){
        HashSet<Character> used = new HashSet<Character>();
        for(int i = 0; i < MAXSIZE; ++i){
            if(board[i][column] != '.' && used.contains(board[i][column])){
                return false;
            }else{
                used.add(board[i][column]);
            }
        }
        return true;
    }

    public boolean judgeSubBox(char[][] board,int row,int column){
        HashSet<Character> used = new HashSet<Character>();
        for(int i = 0; i < SUBBOXSIZE; ++i){
            for (int j = 0; j < SUBBOXSIZE; ++j){
                if(board[row + i][column + j] != '.' && used.contains(board[row + i][column + j])){
                    return false;
                }else{
                    used.add(board[row + i][column + j]);
                }
            }
        }
        return true;
    }
}

方法二

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值