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.


Leetcode 37. Sudoku Solver_第1张图片

A sudoku puzzle...


Leetcode 37. Sudoku Solver_第2张图片

...and its solution numbers marked in red.

分析

向空格填入1-9,填满整个表格。需要依次向空位填值,然后检查该值会不会影响整个表格的合法性。然而由于之前的表格是合法的,所以只需要判断引入的该值所在行列及其方框不冲突即可。
我使用两种递归的方法,及将递归改为堆栈式的如下C代码都能通过。

//判断 加入该数字后是否有效,(boardRowSize,boardColSize)
bool isValid(char** board, int i, int j)  
{  
    for(int k=0;k<9;k++)  
    {  
        if(k!=j && board[i][k]==board[i][j])  
            return false;  
    }  
    for(int k=0;k<9;k++)  
    {  
        if(k!=i && board[k][j]==board[i][j])  
            return false;  
    }          
    for(int row = i/3*3; row=9)
        return solver1(board,i+1,0);
    if(i==9)
        return true;
    if(board[i][j]=='.')
    {
        for(int k=1;k<=9;k++)
        {
            board[i][j]=k+'0';
            if(isValidSudoku(board,i,j)==true)
            {
                if(solver1(board,i,j+1)==true)
                    return true;
            }
            board[i][j]='.';
        }
    }
    else
        return solver1(board,i,j+1);
    return false;
}


void solveSudoku(char** board, int boardRowSize, int boardColSize) {
    int ans=0;
    int emptyi[100]={0},emptyj[100]={0},emptyvalue[100]={0},emptynums=0;
    for(int i=0;i<9;i++)
    {
        for(int j=0;j<9;j++)
        {
            if(board[i][j]=='.')
            {
                emptyi[emptynums]=i;
                emptyj[emptynums]=j;
                emptynums++;
            }
        }
    }
    //solver1(board,0,0);
    //solver2(board,ans,emptynums);
    //方法3 堆栈式 
    while(ans

你可能感兴趣的:(Leetcode 37. Sudoku Solver)