您的位置:首页 > 其它

POJ 2676 SuDoKu DFS

2015-03-13 00:13 302 查看
本打算直接搜索全图,但是又担心会TLE,其实可以把未填空格可以放在数据, 这样就避免了遍历整个图去寻找未填的空格了,

有两点需要注意:

1,输入时要使用scanf("%1d",  ***);

2,标记子方块时用的方法,就是处理方块与子方块的关系

网上有说升序深搜(407MS) 没有 降序深搜快(0MS)

升序: 0 ~ cur-1     降序:cur - 1 ~ 0

升序代码:

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;

#define MAX 10

bool row[MAX][MAX], column[MAX][MAX];
bool sq[4][4][MAX];
int mat[MAX][MAX];

struct Point
{
int x;
int y;
}Node[91];

int cur;
int n;
bool dfs(int cn)
{
if(cn >= cur) return true;
int x = Node[cn].x;
int y = Node[cn].y;

for(int i = 1; i <= 9; i++)
{
if(row[x][i] || column[y][i] || sq[x/3][y/3][i])
continue;
row[x][i] = true;
column[y][i] = true;
sq[x/3][y/3][i] = true;

mat[x][y] = i;
if(dfs(cn + 1)) return true;
row[x][i] = column[y][i] = sq[x/3][y/3][i] = false;
}
return false;
}
int main()
{
while(scanf("%d", &n) == 1)
{
for(int i = 0; i < n; i++)
{
cur = 0;
memset(row, 0, sizeof(row));
memset(column, 0, sizeof(column));
memset(sq, 0, sizeof(sq));
for(int x = 0; x < MAX - 1; x++)
for(int y = 0; y < MAX - 1; y++)
{
scanf("%1d", &mat[x][y]);
if(mat[x][y])
{
row[x][mat[x][y]] = true;
column[y][mat[x][y]] = true;
sq[x/3][y/3][mat[x][y]] = true;
}
else
Node[cur++] = (Point){x, y};
}
dfs(0);

for(int i = 0; i < MAX - 1; i++)
{
for(int j = 0; j < MAX - 1; j++)
{
printf("%d", mat[i][j]);
}
printf("\n");
}
}
}
return 0;
}


降序代码:

#include <cstdio>
#include <iostream>
#include <map>
#include <cstring>

using namespace std;

struct node {
int x, y;
}q[9*9+10];

bool row[10][10], col[10][10], sq[4][4][10];
int G[10][10], cnt;

bool dfs(int cn) {
if(cn < 0) return true;

int x = q[cn].x, y = q[cn].y;

for(int k=1; k<=9; k++) {
if(row[x][k] || col[y][k] || sq[x/3][y/3][k]) continue;
row[x][k] = col[y][k] = sq[x/3][y/3][k] = true;

G[x][y] = k;
if(dfs(cn-1)) return true;

row[x][k] = col[y][k] = sq[x/3][y/3][k] = false;
}

return false;
}

int main() {
int T;
scanf("%d", &T);

while(T--) {
cnt = 0;
memset(row, false, sizeof(row));
memset(col, false, sizeof(col));
memset(sq, false, sizeof(sq));

for(int i=0; i<9; i++) {
for(int j=0; j<9; j++) {
scanf("%1d", &G[i][j]);
int k = G[i][j];
if(k != 0) {
row[i][k] = col[j][k] = sq[i/3][j/3][k] = true;
}
else q[cnt++] = (node){i, j};
}
}

dfs(cnt-1);

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

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: