36. Valid Sudoku

本文介绍了一种验证数独是否有效的算法。通过三种方法实现:一是利用哈希集对数独进行编码并检查重复;二是使用三个哈希集分别记录每行、每列和每个3x3宫格内的数字;三是采用三个9x9数组记录每一行、每一列及每个宫格内1-9的使用情况。

摘要生成于 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.

九宫格规则,横、竖、3*3均没有重复的数,才算成功。最直观的方法是对格子编码,通过hashset判断有没有重复编码,来判断有没有重复数字。用4来举例,如果4在第7行,编码“7(4)”,如果4在第七列,编码“(4)7”,如果4在第0,1个3*3小格,编码“0(4)1”。代码如下:

public class Solution {
    public boolean isValidSudoku(char[][] board) {
        HashSet<String> hs = new HashSet<String>();
        for (int i = 0; i < board.length; i ++) {
            for (int j = 0; j < board[0].length; j ++) {
                if (board[i][j] != '.') {
                    String str = "(" + board[i][j] + ")";
                    if (!hs.add(i + str) || !hs.add(str + j) || !hs.add(i / 3 + str + j / 3)) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
}
另一种方法采用3个hashset分别存储每一行,每一列,每一个cub的数,判断有没有重复。代码如下:

public boolean isValidSudoku(char[][] board) {
    for(int i = 0; i<9; i++){
        HashSet<Character> rows = new HashSet<Character>();
        HashSet<Character> columns = new HashSet<Character>();
        HashSet<Character> cube = new HashSet<Character>();
        for (int j = 0; j < 9;j++){
            if(board[i][j]!='.' && !rows.add(board[i][j]))
                return false;
            if(board[j][i]!='.' && !columns.add(board[j][i]))
                return false;
            int RowIndex = 3*(i/3);
            int ColIndex = 3*(i%3);
            if(board[RowIndex + j/3][ColIndex + j%3]!='.' && !cube.add(board[RowIndex + j/3][ColIndex + j%3]))
                return false;
        }
    }
    return true;
}
还有一种方法采用3个9*9的数组存储每一行、每一列、每一个cub的1-9使用情况。代码如下:

class Solution
{
public:
    bool isValidSudoku(vector<vector<char> > &board)
    {
        int used1[9][9] = {0}, used2[9][9] = {0}, used3[9][9] = {0};
        
        for(int i = 0; i < board.size(); ++ i)
            for(int j = 0; j < board[i].size(); ++ j)
                if(board[i][j] != '.')
                {
                    int num = board[i][j] - '0' - 1, k = i / 3 * 3 + j / 3;
                    if(used1[i][num] || used2[j][num] || used3[k][num])
                        return false;
                    used1[i][num] = used2[j][num] = used3[k][num] = 1;
                }
        
        return true;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值