Leetcode - 037. Sudoku Solver

原题地址

建议解锁 Leetcode - 036. Valid Sudoku 之后再处理本题

我的思路:
1.需要遍历整个解空间求得可行解,隶属 dfs + backtracing
2.需要used数组记录每行,每列,每块的数字占用情况
2.1 初始数组指定一部分const 的占用情况
2.2 dfs的过程中会更新used,backtraing 的过程会抹去上一次的尝试
3.一个隐藏的trick是dfs + backtracing在整体退出之后会回到进入之前的状态,所以退出之后
board会跟原始状态一致,所以需要另外一个board存储解
新手注意:(当时因为这一点困扰了我一个夜晚,dfs + backtraing 又不好debug,蛋疼)

class Solution {
public:

    void dfs(vector> &ans, vector> & board,
        vector> &row, vector> &col, vector> bok,
        int cur_i, int cur_j)
    {
        if (cur_j >= 9)
        {
            cur_j = 0;
            ++cur_i;
        }
        if (cur_i >= 9)
        {
            ans = board;
            return;
        }
        char ch = board[cur_i][cur_j];
        if (ch != '.')
        {
            dfs(ans, board, row, col, bok, cur_i, cur_j + 1);
        }
        // 试图在board[cur_i][cur_j]的位置放上val
        for (int val = 1; val <= 9; ++val)
        {
            int cur_k = 3 * (cur_i / 3) + cur_j / 3;
            if (row[cur_i][val] == 0 && col[cur_j][val] == 0 && bok[cur_k][val] == 0)
            {
                row[cur_i][val] = 1;
                col[cur_j][val] = 1;
                bok[cur_k][val] = 1;
                board[cur_i][cur_j] = char(val + '0');
                dfs(ans, board, row, col, bok, cur_i, cur_j + 1);
                board[cur_i][cur_j] = ch;
                row[cur_i][val] = 0;
                col[cur_j][val] = 0;
                bok[cur_k][val] = 0;
            }
        }
    }

    void solveSudoku(vector>& board) {
        vector> ans;
        vector> row(9, vector(10, 0));
        vector> col(9, vector(10, 0));
        vector> bok(9, vector(10, 0));
        for (int i = 0; i < 9; ++i)
        {
            for (int j = 0; j < 9; ++j)
            {
                char ch = board[i][j];
                if (ch == '.')
                    continue;
                int num = ch - '0';
                int k = 3 * (i / 3) + j / 3;
                row[i][num] = 1;
                col[j][num] = 1;
                bok[k][num] = 1;
            }
        }
        dfs(ans, board, row, col, bok, 0, 0);
        board = ans;
    }
};

你可能感兴趣的:(backtracking,dfs,c++,leetcode)