[leetcode] 37. Sudoku Solver 解题报告

题目链接:https://leetcode.com/problems/sudoku-solver/

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character '.'.

You may assume that there will be only one unique solution.


A sudoku puzzle...


...and its solution numbers marked in red.


思路:和八皇后思路差不多,每一个坑枚举所有的可能,如果一个位置已经有数字了,则跳过这个位置,进入下一个位置,直到一个分支最后可以得到一个解。

在检查一个位置有那些数可利用的时候,可以用一个表来记录各个数的可用状态,这样不用一个个的检查某个数是否可用了。

不知道为啥我的代码效率这么低,骂人

代码如下:

class Solution {
public:
    vector<bool> check(vector<vector<char>> board, int row, int col)
    {
        vector<bool> hash(10, true);
        for(int i = 0; i < 9; i++)
        {
            if(board[row][i] != '.')//检查当前行
                hash[board[row][i] - '0'] = false;
            if(board[i][col] != '.')//检查当前列
                hash[board[i][col] - '0'] = false;
        }
        for(int i = row/3*3; i < row/3*3+3; i++)//检查九宫格
            for(int j = col/3*3; j< col/3*3+3; j++)
                if(board[i][j] != '.')
                    hash[board[i][j] - '0'] = false;
        return hash;
    }
    
    void DFS(vector<vector<char>> board, int row, int col)
    {
        if(col >= 9)//换行
        {
            row++;
            col = 0;
        }
        if(row >= 9)//已经排完所有空格
        {
            cout << "i am here" << endl;
            result = board;
            return;
        }
        if(board[row][col] != '.')  
        {
            col++;
            DFS(board, row, col);
            return;
        }
        
        vector<bool> hash = check(board, row, col);
        for(int i = 1; i<= 9; i++)//枚举每一个可能
        {
            if(hash[i])
            {
                board[row][col] = ('0' + i);
                DFS(board, row, col+1);
            }
        }
    }
    
    void solveSudoku(vector<vector<char>>& board) {
        DFS(board, 0, 0); 
        board = result;
    }
private:
    vector<vector<char>> result;
};


你可能感兴趣的:(LeetCode,DFS,backtracking,深搜)