Leetcode-37: Sudoku Solver

这题也是经典回溯题,跟八皇后很像。

注意:

1) 还是用位运算最方便。
2) dfs参数用一个index就可以了,然后转换成row和col。
3) 如果当前格不是'.',那就跳过去处理下一格。

#include <iostream>
#include <vector>

using namespace std;

vector<int> row(9,0), col(9,0), grids(9,0);

void preprocess(vector<vector<char>>& board) {
    if (board.size()!=9) return;
    for (int i=0; i<9; ++i) {
        if (board[i].size()!=9) return;
        for (int j=0; j<9; ++j) {
            char c=board[i][j];
            if (c!='.') {
                int k=0x1<<(board[i][j]-'0');
                row[i]|=k; col[j]|=k; grids[i/3*3+j/3]|=k;
            }
        }
    }
}

bool dfs(int index, vector<vector<char>>& board) {
    if (index==81)
        return true;

    int r=index/9, c=index%9;

    if (board[r][c]=='.') {
        for (int i=1; i<=9; i++) {   //note: not i=0..8
            int j=0x1<<i;
            if (!(row[r]&j) && !(col[c]&j) && !(grids[r/3*3+c/3]&j)) {
                row[r]|=j; col[c]|=j; grids[r/3*3+c/3]|=j;
                board[r][c]='0'+i;
                if (dfs(index+1, board)) {
                    return true;
                }
                row[r]^=j; col[c]^=j; grids[r/3*3+c/3]^=j;
                board[r][c]='.';
              //  return false; //do not return as we can still try other i !!!
            }
        }
        return false;
    }else {  //if current board unit is number, then continue with dfs on next unit
        return dfs(index+1, board);
    }
}

void solveSudoku(vector<vector<char>>& board) {
    preprocess(board);
    dfs(0, board);
}

int main()
{
    vector<vector<char> >  board{{'5','3','.','.','7','.','.','.','.'},
                                 {'6','.','.','1','9','5','.','.','.'},
                                 {'.','9','8','.','.','.','.','6','.'},
                                 {'8','.','.','.','6','.','.','.','3'},
                                 {'4','.','.','8','.','3','.','.','1'},
                                 {'7','.','.','.','2','.','.','.','6'},
                                 {'.','6','.','.','.','.','2','8','.'},
                                 {'.','.','.','4','1','9','.','.','5'},
                                 {'.','.','.','.','8','.','.','7','9'}};

    solveSudoku(board);

    for (auto i=0; i<9; i++) {
        for (auto j=0; j<9; j++)
            cout<<board[i][j]<<" ";
        cout<<endl;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值