LeetCode 37. Sudoku Solver--回溯法

本文介绍了一种基于回溯法的数独求解算法。通过判断每个空格是否与已填写数字冲突,逐步填充空格直至解决谜题。文章详细解释了如何检查行、列及九宫格内的冲突,并提供了完整的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

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.


解:其实和八皇后的问题是类似的,只是状态和判断冲突复杂了一些,首先要清楚数独的规则,每一行每一列是1~9,每个小九宫格是1~9,(注意对角线不一定是1~9!!),从左上角的位置开始向右向下填,遇到数字直接跳过,当在某个位置没有数字可填时,回溯,注意在回溯过程中要把已经填的数字都恢复到 ‘.’ 原状态,当填到右下角的位置,且那个位置是固定数字or可以找到一个不冲突的数字填入,说明找到了解,代码:

class Solution {
public:
	bool isConflict(int line, int col, char value, vector<vector<char> >& board) {
		for (int i = 0; i < 9; i++) {
			if (board[i][col] == value) return true;
			if (board[line][i] == value) return true;
		}
		int line_no = line/3;
		int col_no = col/3;
		for (int i = 0; i < 3; i++) 
			for (int j = 0; j < 3; j++) 
				if (board[line_no*3+i][col_no*3+j] == value) return true;
		return false;
	}

	bool solveOneStep(int line, int col, vector<vector<char> >& board) {
		if (board[line][col] != '.') {
			if (col == 8 && line == 8) return true;
			if (col == 8) return solveOneStep(line+1, 0, board);
			else return solveOneStep(line, col+1, board);
		}
		bool result = false;
		for (int i = 1; i <= 9; i++) {
			board[line][col] = '.';
			if (!isConflict(line, col, '0'+i, board)) {
				board[line][col] = '0'+i;
				if (line == 8 && col == 8) return true;
				if (col == 8) result = solveOneStep(line+1, 0, board);
				else result = solveOneStep(line, col+1, board);
				if (result) break;
			}
		}
		if (!result) board[line][col] = '.';
		return result;
	}

    void solveSudoku(vector<vector<char> >& board) {
        solveOneStep(0, 0, board);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值