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
    关注
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!