LeetCode 37.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.


A sudoku puzzle...


...and its solution numbers marked in red.

分析与解答:

利用回溯法进行递归的DFS。判断每个位置是不是为'.'。不是就跳过,是就循环遍历1-9填在该位置的合理性。如果合理就继续下一个位置,如果尝试了所有9个数都不合理就回溯。我自己的代码AC了,虽然比较短但是逻辑不是很清晰,贴出一份别人的代码。

class Solution {
  public:
      void solveSudoku(vector<vector<char> > &board) {
        solve(board, 0);
    }
    bool solve(vector<vector<char> > &board , int count) {//递归求解
        if(count >= 81)
            return true;
        int row = count / 9, col = count % 9; //计算坐标
        if(board[row][col] != '.')
            return solve(board, count + 1);
        else {
            for(char c = '1'; c <= '9'; c++) {
                if(isValidRow(board, row, c) && isValidCol(board, col, c) && isValidBox(board, row, col, c)) {
                    board[row][col] = c;
                    if(solve(board, count + 1))
                        return true;
                        else
                    board[row][col] = '.';
                }
            }
        }
        return false;
    }
    bool isValidRow(vector<vector<char> > &board, int row , char c) {
        for(int i = 0; i < 9; i++) {
            if(board[row][i] == c)
                return false;
        }
        return true;
    }

    bool isValidCol(vector<vector<char> > &board, int col , char c) {
        for(int i = 0; i < 9; i++) {
            if(board[i][col] == c)
                return false;
        }
        return true;
    }
    bool isValidBox(vector<vector<char> > &board, int row , int col, char c) {
    int boxR = (row / 3) * 3 , boxC = (col / 3) * 3;  //计算九宫格的第一个坐标
        for(int i = 0; i < 3; i++) {
            for(int j = 0; j < 3; j++) {
                if(board[boxR + i][boxC + j] == c)
                    return false;
            }
        }
        return true;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值