LeetCode 37. Sudoku Solver

题目:
Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once in each column.
Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
Empty cells are indicated by the character ‘.’

The given board contain only digits 1-9 and the character ‘.’.
You may assume that the given Sudoku puzzle will have a single unique solution.
The given board size is always 9x9.

简单的数独填写
很明显可以得出该题采用dfs加上回溯法,改写之前写过的八皇后就完事儿了。

代码如下:

class Solution
{
public:
	bool isValid(vector<vector<char> > &board, int x, int y) //判断现有棋盘状态是否合法
	{
		int i, j;
		for (i = 0; i < 9; i++)
			if (i != x && board[i][y] == board[x][y]) // 横向
				return false;
		for (j = 0; j < 9; j++)
			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;
	}
	bool solveSudoku(vector<vector<char> > &board)
	{
		for (int i = 0; i < 9; ++i)
			for (int j = 0; j < 9; ++j)
			{
				if ('.' == board[i][j]) // 如果为空
				{
					for (int k = 1; k <= 9; ++k) //尝试性填入1~9
					{
						board[i][j] = '0' + k;
						if (isValid(board, i, j) && solveSudoku(board)) // 如果合法,返回true
							return true;
						board[i][j] = '.'; // 之前的填法都不合法,回溯的将之前填过的空置空5
					}
					return false; // 如果1~9都没有解出来,返回错误。
				}
			}
		return true;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值