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.


思想:

首先,设置布尔型变量,用于存储图中哪些位已经填充,true表示已填充,false,表示未填充。初始化完毕以后,从(0,0)坐标处对图进行搜索,搜索方式(横向扫描),此方法可以采用递归来解决。


代码:

class Solution {
public:
	bool row[9][10] ;
	bool col[9][10] ;
	bool box[9][10] ;
	bool solve(vector<vector<char> >&board, int i, int j)
	{
		if (i >= 9) return true;
		if (board[i][j] != '.')
			return solve(board, i + (j + 1) / 9, (j + 1) % 9);//深度优先搜索
		for (int k = 1; k < 10; ++k)
		{
			if (!row[i][k] && !col[j][k] && !box[i / 3 * 3 + j / 3][k])
			{
				board[i][j] = k + '0';
				row[i][k] = true;
				col[j][k] = true;
				box[i / 3 * 3 + j / 3][k] = true;
				if (solve(board, i + (j + 1) / 9, (j + 1) % 9))
					return true;
				board[i][j] = '.';//不满足,则返回上一步
				row[i][k] = false;
				col[j][k] = false;
				box[i / 3 * 3 + j / 3][k] = false;
			}
		}
		return false;
	}
	void solveSudoku(vector<vector<char> >& board) {
		memset(row, 0, sizeof(row));
		memset(col, 0, sizeof(col));
		memset(box, 0, sizeof(box));
		for (int i = 0; i < 9; i++)
		{
			for (int j = 0; j < 9; ++j)
			{
				char c = board[i][j];
				if (c != '.')
				{
					row[i][c - '0'] = true;
					col[j][c - '0'] = true;
					box[i / 3 * 3 + j / 3][c - '0'] = true;
				}
			}
		}
		solve(board, 0, 0);
	}
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值