数独

本文介绍了一个Sudoku求解器程序的实现方法,通过深度优先搜索(DFS)策略遍历空格并尝试填充数字,确保每一步操作都符合Sudoku的规则。代码使用C++编写,展示了如何检查每一步填充的合法性。

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

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放数,如果合法继续,否则返回。


#include <iostream>

using namespace std;

char board[9][9];

// LeetCode, Sudoku Solver
// 时间复杂度O(9^4),空间复杂度O(1)
class Solution {
public:
    bool solveSudoku(char board[][9]) {
        for (int i = 0; i < 9; ++i)
            for (int j = 0; j < 9; ++j) {
                if (board[i][j] == '.') {
                    for (int k = 0; k < 9; ++k) {
                        board[i][j] = '1' + k;
                        if (isValid(board, i, j) && solveSudoku(board))
                            return true;
                        board[i][j] = '.';
                    }
                    return false;
                }
            }
        return true;
    }
private:
    // 检查 (x, y) 是否合法
    bool isValid(char board[][9], int x, int y) {
        int i, j;
        for (i = 0; i < 9; i++) // 检查 y 列
            if (i != x && board[i][y] == board[x][y])
                return false;
        for (j = 0; j < 9; j++) // 检查 x 行
            if (j != y && board[x][j] == board[x][y])
                return false;
        for (i = 3 * (x / 3); i < 3 * (x / 3 + 1); i++)
            for (j = 3 * (y / 3); j < 3 * (y / 3 + 1); j++)
                if ((i != x || j != y) && board[i][j] == board[x][y])
                    return false;
        return true;
    }
};


int main()
{
	int T;

	cin >> T;
	while(T--) {
		for(int i=0; i<9; i++)
			for(int j=0; j<9; j++)
				cin >> board[i][j];

		Solution s;
		bool ans = s.solveSudoku(board);
		if (ans) {
			for(int i=0; i<9; i++) {
				for(int j=0; j<9; j++)
					cout << board[i][j] << " ";
				cout << endl;
			}
		} else
			cout << "no solution" << endl;
		cout << endl;
	}
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值