天天看點

LeetCode-37-Sudoku Solver

算法描述:

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

A sudoku solution must satisfy all of the following rules:

  1. Each of the digits 

    1-9

     must occur exactly once in each row.
  2. Each of the digits 

    1-9

     must occur exactly once in each column.
  3. Each of the the digits 

    1-9

     must occur exactly once in each of the 9 

    3x3

     sub-boxes of the grid.

Empty cells are indicated by the character 

'.'

.

解題思路:采用回溯法,每次嘗試一個數字并判斷合法性。如果不合法,則傳回并恢複棋盤。

void solveSudoku(vector<vector<char>>& board) {
        if(board.size()==0 || board[0].size()==0) return;
        solve(board);
    }
    
    bool solve(vector<vector<char>>& board){
        for(int i=0; i < board.size(); i++){
            for(int j=0; j < board[0].size(); j++){
                if(board[i][j]=='.'){
                    for(char c = '1'; c <= '9'; c++){
                        if(isValid(board,i,j,c)){
                            board[i][j] = c;
                            
                            if(solve(board)) return true;
                            
                            board[i][j] = '.';
                        }
                    }
                    return false;
                }
                
            }
        }
        return true;
    }
    
    bool isValid(vector<vector<char>> &board, int row, int col, char c){
        for(int i =0; i < 9; i++){
            if(board[row][i]!='.' && board[row][i]==c) return false;
            if(board[i][col]!='.' && board[i][col]==c) return false;
            if(board[3*(row/3)+i/3][3*(col/3)+i%3]!='.' && board[3*(row/3)+i/3][3*(col/3)+i%3]==c) return false;   
        }
        return true;
    }      

轉載于:https://www.cnblogs.com/nobodywang/p/10363081.html