leetcode[37]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.

#define NUM 9
class Solution {
public:
bool isValidij(vector<vector<char> > &board, int i, int j) 
{
    for (int k=0;k<NUM;k++)
    {
        if (k!=j)
        {
            if(board[i][k]==board[i][j])return false;
        }
        if (k!=i)
        {
            if(board[k][j]==board[i][j])return false;
        }
    }
    int a=i/3*3;
    int b=j/3*3;
    for (int ii=a;ii<a+3;ii++)
    {
        for (int jj=b;jj<b+3;jj++)
        {
            if(ii!=i&&jj!=j)
            {
                if (board[ii][jj]==board[i][j])return false;
            }
        }
    }
    return true;
}
bool solve(vector<vector<char> > &board) 
{
    for (int i=0;i<NUM;i++)
    {
        for (int j=0;j<NUM;j++)
        {
            if (board[i][j]=='.')
            {
                int k=1;
                for (;k<=NUM;k++)
                {
                    board[i][j]='0'+k;
                    if (isValidij(board,i,j))
                    {
                        if(solve(board))return true;
                    }
                    board[i][j]='.';
                }
                return false;
            }
        }
    }
    return true;
}
void solveSudoku(vector<vector<char> > &board) 
{
        solve(board);
}
};
原文地址:https://www.cnblogs.com/Vae1990Silence/p/4283592.html