首页 > 其他 > 详细

LeetCode-37-Sudoku Solver

时间:2019-02-11 20:33:58      阅读:181      评论:0      收藏:0      [点我收藏+]

算法描述:

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;
    }

 

LeetCode-37-Sudoku Solver

原文:https://www.cnblogs.com/nobodywang/p/10363081.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!