【算法day32】解数独重写——编写一个程序,通过填充空格来解决数独问题

37. 解数独

编写一个程序,通过填充空格来解决数独问题。

数独的解法需 遵循如下规则:

数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)
数独部分空格内已填入了数字,空白格用 ‘.’ 表示。

https://leetcode.cn/problems/sudoku-solver/
在这里插入图片描述

class Solution {
public:
    bool cols[9][9];
    bool rows[9][9];
    bool cubes[9][9];
    vector<pair<int, int>> positions;
    bool valid = false;

    void dps(vector<vector<char>>& board, int pos) {
        if (pos == positions.size()) {
            valid = true;
            return;
        }
        auto [x, y] = positions[pos];
        for (int num = 0; num < 9 && !valid; num++) {
            if (!cols[x][num] && !rows[y][num] && !cubes[((int)(x / 3)) * 3 + (y / 3)][num]) {
                cols[x][num] = 1;
                rows[y][num] = 1;
                cubes[((int)(x / 3)) * 3 + (y / 3)][num] = 1;
                board[x][y] = num + 1 + '0';
                dps(board, pos + 1);
                cols[x][num] = 0;
                rows[y][num] = 0;
                cubes[((int)(x / 3)) * 3 + (y / 3)][num] = 0;
            }
        }
    }

    void solveSudoku(vector<vector<char>>& board) {
        memset(cols, 0, sizeof(cols));
        memset(rows, 0, sizeof(rows));
        memset(cubes, 0, sizeof(cubes));
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                if (board[i][j] != '.') {
                    int num = board[i][j] - '0' - 1;
                    cols[i][num] = 1;
                    rows[j][num] = 1;
                    cubes[((int)(i / 3)) * 3 + (j / 3)][num] = 1;
                } else {
                    // 空的
                    positions.emplace_back(i, j);
                }
            }
        }
        dps(board, 0);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值