码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 37. Sudoku Solver

时间:2019-10-01 09:16:35      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:dex   from   The   fill   aci   ++   bsp   cto   bee   

经典backtracing的问题。我们可以记录每行,每列,每个box那些数字出现过,快速判断当前填入的数字是否有重复。

class Solution {
public:
    vector<vector<bool>> rowhash; // rowhash[row][1~9] - if the number has been taken in row
    vector<vector<bool>> colhash; // colhash[col][1~9] - if the number has been taken in col
    vector<vector<bool>> boxhash; // box are indexed by 0~8, from left to right, top to bottom
    
    void solveSudoku(vector<vector<char>>& board) {
        int m=board.size(), n=m==0?0:board[0].size();
        if (m==0 || n==0) return;
        
        rowhash.resize(9,vector<bool>(10,false));
        colhash.resize(9,vector<bool>(10,false));
        boxhash.resize(9,vector<bool>(10,false));
        
        for (int i=0;i<m;++i){
            for (int j=0;j<n;++j){
                if (board[i][j]==.) continue;
                int num=board[i][j]-0;
                rowhash[i][num] = true;
                colhash[j][num] = true;
                boxhash[i/3*3+j/3][num] = true; // i/3, j/3
            }
        }
        backtrack(board,0,0);
    }
    
    bool backtrack(vector<vector<char>> &board, int i, int j){
        if (i==9) return true;
        if (board[i][j]!=.){
            auto [next_i,next_j] = nextPos(i,j);
            return backtrack(board,next_i,next_j);
        }else{
            // select a number to fill in the blank
            for (int k=1;k<=9;++k){
                if (!rowhash[i][k] && !colhash[j][k] && !boxhash[i/3*3+j/3][k]){
                    board[i][j] = k+0;
                    rowhash[i][k] = colhash[j][k] = boxhash[i/3*3+j/3][k] = true;
                    auto [next_i,next_j] = nextPos(i,j);
                    if (backtrack(board,next_i,next_j))
                        return true;
                    board[i][j] = .;
                    rowhash[i][k] = colhash[j][k] = boxhash[i/3*3+j/3][k] = false;
                }
            }
        }
        return false;
    }
    
    pair<int,int> nextPos(int i, int j){
        if (j==8) return {i+1,0};
        else return {i,j+1};
    }
};

上述方法是dfs(i,j),导致没到一行的末尾要换行,比较繁琐。

可以把所有空格都放到一个vector里,dfs这个vector的下标即可。

 

LeetCode 37. Sudoku Solver

标签:dex   from   The   fill   aci   ++   bsp   cto   bee   

原文地址:https://www.cnblogs.com/hankunyan/p/11614569.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!