LeetCode 37 Sudoku Solver

37. Sudoku Solver

Total Accepted: 48148 Total Submissions: 195066 Difficulty: Hard

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.

Subscribe to see which companies asked this question

Have you met this question in a real interview?


解数独。

经典问题了

DFS+回溯

把以前POJ那道题的代码稍稍改改就过了。


class Solution {
    
private:
    bool issolve=false;
    vector<vector<char>> graph;
    
public:
    bool isOk(int x,int y,int value)
    {  
        for(int i=0;i<9;i++)  
                if(graph[i][y]-'0'==value||graph[x][i]-'0'==value)  
                        return false;  
        int sx=x/3*3,sy=y/3*3;  
        for(int i=sx;i<sx+3;i++)  
                for(int j=sy;j<sy+3;j++)  
                        if(graph[i][j]-'0'==value)  
                                return false;  
        return true;  
    }  

    void dfs(int k){  
        if(k==81)  
        {  
                issolve=true;  
                return;  
        }  
        int x=k/9,y=k%9;  
        if(graph[x][y]!='.')  
                dfs(k+1);  
        else  
                for(int i=1;i<=9;i++)  
                        if(isOk(x,y,i))  
                        {  
                                graph[x][y]=i+'0';  
                                dfs(k+1);  
                                if(issolve)  
                                        return;  
                                graph[x][y]='.';  
                        }  
    }  
    void solveSudoku(vector<vector<char>>& board) {
        graph=board;
        dfs(0);
        board=graph;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值