qq_34479762 2016-12-08 15:29 采纳率: 0%
浏览 961

(poj-2767)新手暴力搜索soduko时,分别用两种深度优先搜索,其中一个不知错在哪里,求问。

正确版本
int DFS(int x, int y)
{
if(x == 9)
return 1;
if(y == 9)
return DFS(x + 1, 0);
if(Map[x][y] != '0')
return DFS(x, y + 1);
for(int i = 0; i < 9; i++)
{
if(! RowUsed[x][i] && ! ColUsed[y][i] && ! BlockUsed[x / 3 * 3 + y / 3][i])
{
RowUsed[x][i] = ColUsed[y][i] = BlockUsed[x / 3 * 3 + y / 3][i] = 1;
Map[x][y] = i + '1';
if(DFS(x, y + 1))
return 1;
RowUsed[x][i] = ColUsed[y][i] = BlockUsed[x / 3 * 3 + y / 3][i] = 0;
Map[x][y] = '0';
}
}
return 0;
}
错误版本
void DFS(int x, int y) {
if(x == 9)
return ;
if(y == 9)
DFS(x + 1, 0);
if(Map[x][y] != '0')
DFS(x, y + 1);
for(int i = 0; i < 9; i++) {
if(!RowUsed[x][i] && !ColUsed[y][i] && !BlockUsed[x / 3 * 3 + y / 3][i]) {
Map[x][y] = i + '1';
RowUsed[x][i] = ColUsed[y][i] = BlockUsed[x / 3 * 3 + y / 3][i] = 1;
DFS(x, y + 1);
Map[x][y] = 0;
RowUsed[x][i] = ColUsed[y][i] = BlockUsed[x / 3 * 3 + y / 3][i] = 0;
}
}
}
完整正确程序
#include
#include

const int MAXN = 9;

char Map[MAXN + 1][MAXN + 1];
int RowUsed[MAXN][MAXN], ColUsed[MAXN][MAXN], BlockUsed[MAXN][MAXN];

int DFS(int x, int y)
{
if(x == 9)
return 1;
if(y == 9)
return DFS(x + 1, 0);
if(Map[x][y] != '0')
return DFS(x, y + 1);
for(int i = 0; i < 9; i++)
{
if(! RowUsed[x][i] && ! ColUsed[y][i] && ! BlockUsed[x / 3 * 3 + y / 3][i])
{
RowUsed[x][i] = ColUsed[y][i] = BlockUsed[x / 3 * 3 + y / 3][i] = 1;
Map[x][y] = i + '1';
if(DFS(x, y + 1))
return 1;
RowUsed[x][i] = ColUsed[y][i] = BlockUsed[x / 3 * 3 + y / 3][i] = 0;
Map[x][y] = '0';
}
}
return 0;
}

int main() {
int Cases;
scanf("%d", &Cases);
while(Cases--) {
memset(RowUsed, 0, sizeof(RowUsed));
memset(ColUsed, 0, sizeof(ColUsed));
memset(BlockUsed, 0, sizeof(BlockUsed));
for(int i = 0; i < 9; i++)
scanf("%s", Map[i]);
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
if(Map[i][j] != '0') {
RowUsed[i][Map[i][j] - '1'] = ColUsed[j][Map[i][j] - '1'] = BlockUsed[i / 3 * 3 + j / 3][Map[i][j] - '1'] = 1;
}
}
}
DFS(0, 0);
for(int i = 0; i < 9; i++)
printf("%s\n", Map[i]);
}
return 0;

}
题目链接:http://poj.org/problem?id=2676

  • 写回答

1条回答 默认 最新

  • threenewbee 2016-12-08 15:48
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧