poj 2676 Sudoku dfs 深搜

[color=blue][size=medium]
题目描述: [url]http://poj.org/problem?id=2676[/url]
[/color][/size][color=red][size=medium]
转自: [url]http://zhangjian110518.blog.163.com/blog/static/74991703200933092722785/[/url]
[/color][/size][size=medium][color=blue]
题目技巧性不强,DFS过的,用时16MS。不过写的过程中要注意从后面往前搜。
[/color][/size]


/************************************************************************/
/*思路:
先从后面开始搜,也就是从第八十个开始搜
1、如果一个小的方格内已经包含了非零的数,则继续向下搜
2、如果一个小的方格内是一个零数,也就是还没有放入相应的数,则对其从零到九开始尝试
3、对每一个数的尝试,检查其合法性:在其所在的3*3方格内是否合适;在此行是否合适:在此列是否合适
4、如果经过以上条件可以的话那么这个数字就可以放在此小方格上,然后继续进行搜索。
************************************************************************/

#include <cstdio>

const int n = 9;
int board[9][9];
char ch[10];

//返回当前board[x][y]中的值是否可行
bool ok(int x, int y) {
// 3 * 3
for (int i = x / 3 * 3; i < x / 3 * 3 + 3; ++i) {
for (int j = y / 3 * 3; j < y / 3 * 3 + 3; ++j) {
if (x == i && y == j)
continue;
if (board[x][y] == board[i][j]) // the number has been used
return false;
}
}
int temp = board[x][y];
// check the row
for (int j = 0; j < n; ++j) {
if (j == y)
continue;
if (board[x][j] == temp)
return false;
}
// check the column
for (int i = 0; i < n; ++i) {
if (i == x)
continue;
if (board[i][y] == temp)
return false;
}
return true; // ok
}


int dfs(int location) {
if (location == -1)
return 1;

if (board[location / n][location % n] != 0) // has number
return dfs(location - 1);
else {
for (int i = 1; i <= n; ++i) { // try
board[location / n][location % n] = i;
if (ok(location / n, location % n)) {
if (dfs(location - 1))
return 1;
}
board[location / n][location % n] = 0;
}
}
return 0;
}

int main() {
int nCases;
scanf("%d", &nCases);
while (nCases--) {
for (int i = 0; i < n; ++i) {
scanf("%s", ch);
for (int j = 0; j < n; ++j) {
board[i][j] = ch[j] - '0';
}
}

dfs(80);

for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
printf("%d", board[i][j]);
}
printf("\n");
}
}

return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值