LeetCode 37.Sudoku Solver题目解析

Description

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.

题目复述

    给你一个数独游戏棋盘,找出一组答案。题目保证只有一个解。

    数独游戏规则:

        (1).同行数字不重复,即为1,2,3,4,5,6,7,8,9

        (2).同列数字不重复,同(1)

        (3).每个3*3小格子内的数字也不重复,同(1)

题目解析

 

1.暴力枚举法

    因为每个待填的格子会有多个待填的值,因此我们采用深度优先遍历的方法搜索答案,从左到右从上到下遇到空格依次枚举填写[1-9]9个数字。如果填了某个数字和规则冲突,则可以剪枝。

    在实现的时候待填的格子用一个整数dept表示,当前行r(dept/列宽)和列c(dept%列宽)都可以从dept解析出来。

class Solution {
public:
     
    //检查r行c列是不是可以填num
    bool check(int r, int c, int num, vector<vector<char>>& board) {
        //检查行
        for(int i=0; i<board[0].size(); i++) {
            if(board[r][i] == '.') continue;
            if(board[r][i]-'0' == num) return false;
        }
        //检查列
        for(int i=0; i<board.size(); i++) {
            if(board[i][c] == '.') continue;
            if(board[i][c]-'0' == num) return false;
        }
        //检查方块
        for(int i=(r/3)*3; i<(r/3)*3+3; i++)
            for(int j=(c/3)*3; j<(c/3)*3+3; j++) {
                if(board[i][j] == '.') continue;
                if(board[i][j]-'0' == num) return false;
            }
        return true;
    }
     
    bool dfs(int dept, vector<vector<char>>& board) {
        if(dept == board.size()*board[0].size()) return true;
         
        bool res = false;   //是否找到解
        int r = dept/board[0].size(), c = dept%board[0].size();
        if(board[r][c] != '.') return dfs(dept+1, board);
        else {
            for(int num=1; num<=9; num++) {  //枚举要填的数
                bool can = check(r, c, num, board);
                if(!can) continue;          //发现不满足规则,剪枝。
                board[r][c] = num + '0';
                res = res || dfs(dept+1, board);
                if(res) break;        //找到答案 直接跳出
                board[r][c] = '.';
            }
        }
        return res;
    }
    void solveSudoku(vector<vector<char>>& board) {
        dfs(0, board);
    }
};

欢迎关注微信公众号 wowAC,随时随在手机上查看权威的LeetCode题目以及解析,并提供原创的算法与数据结构课程。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值