[recommend for beginners]clean C++ implementation with detailed explanation


  • -1

    WHAT IS the problem with my code ? My implementation just return without storing the final valid result!!!!

    class Solution {
        public:
             void solveSudoku(vector<vector<char>>& board) {
                 solve(board);
                 return;
             }
            
             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=0; k<9; k++){
                                board[i][j]='1'+k;
                                /*** check all the position util return true ***/
                                if(isValid(board, i, j)){
                                    if(solve(board))    return true;
                                }
                                board[i][j]='.';
                            }
                            /*** can not find solution for the first '.' position ***/
                            return false;
                        }
                    }
                }
                return true;
            }
            
            bool isValid(const vector<vector<char>> &board, int x, int y){
                int i, j;
                /*** check column y ***/
                for(i=0; i<9; i++){
                    if(i!=x && board[i][y]==board[x][y])  return false;
                }
                /*** check row x ***/
                for(j=0; j<9; j++){
                    if(j!=y && board[x][j]==board[x][y])  return false;
                }
                /*** check the cute ***/
                for(i=3*(x/3); i<3*(x/3+1); i++){
                    for(j=3*(y/3); j<3*(y/3+1); j++){
                        if((i!=x || j!=y) && board[i][j]==board[x][y])
                            return false;
                    }
                }
                return true;
            }
        };

  • 0

    I fix the bug by finding that in the last loop I mistake type 2 as 1 ....... 233333


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.