Leetcode -- Sudoku Solver

来源:互联网 发布:怎么校准网络时间 编辑:程序博客网 时间:2024/05/02 02:29

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.

分析:

首先意识到这是个递归的结构:每次添加一个数,相当于一个新的board;

求解时,对每个需要填充的位置,找到一个合法的数,并以此为新的board,进行递归求解。这时可能出现三种情况:

1. 找不到需要填充的位置,也即整个board都被正确的填充了,求解完成;

2. 在某个位置上可以一直找到最终的解,这时返回true;

3. 在某个位置上找不到任何可以填充的数,这说明之前的某一步是不合法的,直接返回false;

class Solution {public:    bool check(vector<vector<char>>& board,int x,int y)    {        for(int i=0;i<9;++i)//row x        {            if(i==y) continue;            if(board[x][i]==board[x][y]) return 0;        }        for(int i=0;i<9;++i)        {            if(i==x) continue;            if(board[i][y]==board[x][y]) return 0;        }        int px = (x/3)*3,py=(y/3)*3;        for(int i=0;i<3;++i)        for(int j=0;j<3;++j)        {            if(px+i==x&&py+j==y) continue;            if(board[px+i][py+j]==board[x][y]) return 0;        }        return 1;    }    bool solve(vector<vector<char>>& board) {        for(int i=0;i<9;++i)            for(int j=0;j<9;++j)                if(board[i][j]=='.')                {                    for(char x='1';x<='9';++x)                    {                        board[i][j]=x;                        if(check(board,i,j)&&solve(board)) return 1;                        board[i][j]='.';                    }                    return 0;                }        return 1;    }    void solveSudoku(vector<vector<char>>& board) {        solve(board);    }};


0 0