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.

    

    ② Its solution numbers marked in red.

    

分析:
    题意:给定数独游戏当前一个局面('.'表示空格,未填写),返回所有空格填写完成的局面。假设只存在唯一解。
    思路:此题是LeetCode 36进化版本。因为要求填写所有空格,因此采用DFS搜索。对于每一个空格,尝试1→9个数字,每一个数字都需要对每行、每列、每个小矩阵三条规则进行判断(若存在重复数字,表明当前填写数字不符合)。① 若当前空格填写完成、从当前局面继续搜索完成所有填写,则返回true表示完成;② 若当前空格尝试9个数字均返回false,表示无法完成,需要返回之前的搜索局面、重新搜索。③ 完成所有空格填写之后,返回true表示完成。

代码:

#include <bits/stdc++.h>

using namespace std;

// DFS
class Solution {
private: 
	bool check(vector<vector<char>>& board, int x, int y, char c){
		// rows ans columns
		for(int i = 0; i <= 8; i++){
			if(board[x][i] == c){
				return false;
			}
			if(board[i][y] == c){
				return false;
			}
		}
		// cubes
		int xx = (x / 3) * 3, yy = (y / 3) * 3;
		for(int i = 0; i <= 2; i++){
			for(int j = 0; j <= 2; j++){
				if(board[xx + i][yy + j] == c){
					return false;
				}
			}
		}
		return true;
	}

	bool DFS(vector<vector<char>>& board){
        for(int i = 0; i <= 8; i++){
			for(int j = 0; j <= 8; j++){
				if(board[i][j] == '.'){
					for(int k = 1; k <= 9; k++){
						if(check(board, i, j, k + '0')){
							board[i][j] = k + '0';
							if(DFS(board)){
								return true;
							}
							else{
								board[i][j] = '.';
							}
						}
					}
					return false;
				}
			}
		}
		return true;
	}
	
public:
    void solveSudoku(vector<vector<char>>& board) {
		DFS(board);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值