Algorithms practice:leetcode37 Sudoku Solver

Description

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once in each column.
Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
The ‘.’ character indicates empty cells.

Example

在这里插入图片描述
Input: board = [[“5”,“3”,“.”,“.”,“7”,“.”,“.”,“.”,“.”],[“6”,“.”,“.”,“1”,“9”,“5”,“.”,“.”,“.”],[“.”,“9”,“8”,“.”,“.”,“.”,“.”,“6”,“.”],[“8”,“.”,“.”,“.”,“6”,“.”,“.”,“.”,“3”],[“4”,“.”,“.”,“8”,“.”,“3”,“.”,“.”,“1”],[“7”,“.”,“.”,“.”,“2”,“.”,“.”,“.”,“6”],[“.”,“6”,“.”,“.”,“.”,“.”,“2”,“8”,“.”],[“.”,“.”,“.”,“4”,“1”,“9”,“.”,“.”,“5”],[“.”,“.”,“.”,“.”,“8”,“.”,“.”,“7”,“9”]]
Output: [[“5”,“3”,“4”,“6”,“7”,“8”,“9”,“1”,“2”],[“6”,“7”,“2”,“1”,“9”,“5”,“3”,“4”,“8”],[“1”,“9”,“8”,“3”,“4”,“2”,“5”,“6”,“7”],[“8”,“5”,“9”,“7”,“6”,“1”,“4”,“2”,“3”],[“4”,“2”,“6”,“8”,“5”,“3”,“7”,“9”,“1”],[“7”,“1”,“3”,“9”,“2”,“4”,“8”,“5”,“6”],[“9”,“6”,“1”,“5”,“3”,“7”,“2”,“8”,“4”],[“2”,“8”,“7”,“4”,“1”,“9”,“6”,“3”,“5”],[“3”,“4”,“5”,“2”,“8”,“6”,“1”,“7”,“9”]]
Explanation: The input board is shown above and the only valid solution is shown below:
在这里插入图片描述

Constraints

board.length == 9
board[i].length == 9
board[i][j] is a digit or ‘.’.
It is guaranteed that the input board has only one solution.

code

class Solution {
    
    
public:
    void solveSudoku(vector<vector<char>>& board) {
    
    
        Backtracking(0,0, board);
    }

    bool Backtracking(int row, int col,vector<vector<char>>& board)
    {
    
    
        //cout<<row<<" , "<<col<<endl;
        if(row == 9)
        {
    
    
            return true;
        }
        if(col == 9)
        {
    
    
            return Backtracking(row+1, 0,board);
        }
        if(board[row][col]=='.')
        {
    
    
            for(int num=1; num<10;num++)
            {
    
    
                if(positionValid(row,col,num,board))
                {
    
    
                    board[row][col]=num+'0';
                    if(Backtracking(row, col+1,board))
                    {
    
    
                        cout<<num;
                        return true;
                    }
                    else
                        board[row][col]='.';
                }
            }
            return false;
        }
        else
            return Backtracking(row,col+1,board);
    }

    bool positionValid(int row, int col, int value,vector<vector<char>>& board)
    {
    
    
        char v = value + '0';
        auto rowIter = board[row].begin();
        while(rowIter != board[row].end())
        {
    
    
            if(v == *rowIter)
            {
    
    
                return false;
            }
            rowIter++;
        }

        auto boardIter = board.begin();
        while(boardIter !=board.end())
        {
    
    
            char colValue= (*boardIter)[col];
            if(v == colValue)
            {
    
    
                return false;
            }
            boardIter++;
        }

        int subRow = int(row/3)*3;
        int subCol = int(col/3)*3;
        for(int i =subRow; i<subRow+3;i++)
        {
    
    
            for(int j= subCol;j<subCol+3;j++)
            {
    
    
                char subValue= board[i][j];
                if(v == subValue)
                {
    
    
                    return false;
                }
            }
        }
        return true;
    }
};


Oral process of solving problems

I will use backtracking algorithms to solve the Sudoku problem. In each Recursive loop, I want to fill those cells by making choices. I think about this compartmentalizing into subproblems. firstly, I focus on a row which means that I solve it one column by one column. when I finish one row, then move to the next row. after I finish all rows, the problem will be solved. So I define my function like this:

bool Backtracking(int row, int col,vector<vector<char>>& board)
{
    
    
	if(row == 9)
     {
    
    // finshing all row means finish problem
         return true;
     }
     if(col == 9) // out of column means we can change row
     {
    
    
         return Backtracking(row+1, 0,board);
     }
     ...
     // next column
     if(Backtracking(row, col+1,board))
     {
    
    
     }
     ...
}

for each cell, I can place numbers 1 through 9 in the cell if it’s empty. then, I need to express my constraints. the thing is when we place an item, I could validate the whole Sudoku board. considered a possible number, I have to check if it is a unique number in a row, in a column, as well as in a subgrid. I write a function named “positionValid”. if that was a valid placement, I recurse on it. I will put the number over here, and go to the next column for this row, or begin of the next row.

    bool positionValid(int row, int col, int value,vector<vector<char>>& board)
    {
    
    
        char v = value + '0';
        auto rowIter = board[row].begin();
        while(rowIter != board[row].end())
        {
    
    
            if(v == *rowIter)
            {
    
    
                return false;
            }
            rowIter++;
        }

        auto boardIter = board.begin();
        while(boardIter !=board.end())
        {
    
    
            char colValue= (*boardIter)[col];
            if(v == colValue)
            {
    
    
                return false;
            }
            boardIter++;
        }

        int subRow = int(row/3)*3;
        int subCol = int(col/3)*3;
        for(int i =subRow; i<subRow+3;i++)
        {
    
    
            for(int j= subCol;j<subCol+3;j++)
            {
    
    
                char subValue= board[i][j];
                if(v == subValue)
                {
    
    
                    return false;
                }
            }
        }
        return true;
    }

for each empty cell, I will try all possible numbers from 1 to 9. for each possible number, I will check if the position is valid. if ok, I will put the number and go to the next empty cell. if not, I will put the cell empty and try another number. if all number is wrong, it means that I have to Backtrack the previous decision and modify the previous cell. So I return false.

        if(board[row][col]=='.')
        {
    
    
            for(int num=1; num<10;num++)
            {
    
    
                if(positionValid(row,col,num,board))
                {
    
    
                    board[row][col]=num+'0';
                    if(Backtracking(row, col+1,board))
                    {
    
    
                        cout<<num;
                        return true;
                    }
                    else
                        board[row][col]='.';
                }
            }
            return false;
        }
        else
            return Backtracking(row,col+1,board);

words

link

leetcode 37. Sudoku Solver
mit : Puzzle 8: You Won’t Want to Play Sudoku Again
Sudoku Solver
https://en.wikipedia.org/wiki/Mathematics_of_Sudoku

猜你喜欢

转载自blog.csdn.net/fuyouzhiyi/article/details/128216601