[LeetCode]037-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.

Solution:
思路,类似于回溯法,层层遍历,直到最后,返回true,否则返回false。
回溯法要注意判断函数,即check,判断当前要插入的值在横向、纵向、子方格内都是合法的。

代码如下:

 void solveSudoku(vector<vector<char>>& board) 
    {
        solve(board);
    }

    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(int k = 1;k<=9;k++)
                    {
                        board[i][j] = k + '0';
                        if(isValid(board,i,j) && solve(board))
                            return true;
                        board[i][j] = '.';
                    }
                    return false;
                }
            }
        }
        return true;
    }

    bool isValid(vector<vector<char>>& board,int row,int col)
    {
        int i,j;
        i = j = 0;
        for(i =0;i<9;i++)
        {
            if(i != row && board[row][col] == board[i][col])
                return false;
        }

        for(j = 0;j<9;j++)
        {
            if(j != col && board[row][col] == board[row][j])
                return false;
        }

        int grid_row = row/3 * 3;
        int grid_col  = col/3 * 3;
        for(i =0;i<3;i++)
            for(j =0;j<3;j++)
            {
                if(row != i+grid_row && col != j + grid_col && board[i+grid_row][j+grid_col] == board[row][col])
                    return false;
            }

        return true;
    }

参考到一个比较简略关键思路清晰的算法:
http://blog.csdn.net/aivin24/article/details/33346657

你可能感兴趣的:(LeetCode)