【发布时间】:2016-07-06 06:40:11
【问题描述】:
我参考了许多文章和问题来回答如何有效地解决迷宫问题,但在这里我想确认我的代码出了什么问题。考虑迷宫:
2 1 0 0 3
0 1 0 1 1
0 1 0 0 1
0 1 1 0 0
0 0 0 0 0
其中 1 代表墙壁,0 代表路径。(来源为 2,目的地为 3)。 我必须输出是否有路径。
int y=0;
while(y==0)
{
robo1(n,m,maze);//this function adds 2 to any '0'/'3' in (i,j+1),(i+1,j),(i-1,j),(i,j-1) (if exists),where (i,j) is 2
robo2(n,m,k2,maze);//this function adds 3 to any '0'/'2' in (i,j+1),(i+1,j),(i-1,j),(i,j-1) (if exists), where (i,j) is 3
if(find5(n,m,maze)==1)//this function returns 1 if there is '5' in the maze
y++;
if(find0(n,m,maze)==0)//this function returns 0 if there are no '0' in the maze
break;
}
if(find0(n,m,maze)==0 && y==0)
printf("-1\n");//no path
else
printf("1\n");//there is a path
我的想法是,如果经过任意数量的循环后,在迷宫中发现了一个 5,那么这意味着有一条路径。 但是在代码中实现这个功能时,我得到了错误的答案,有时还会出现运行时错误。 上面的逻辑有什么缺陷吗?
【问题讨论】:
-
请提供
robo1、robo2、find5、find0的实现。运行时错误意味着您可能会超出任何这些函数的范围,但如果没有代码就很难判断 -
对我来说还不清楚这种方法是什么。你知道depth first search吗?
-
问题很可能出在
robo*和find*,所以请按照@buld0zzr 的说法发布。这里的逻辑我认为没关系(虽然它不是“最好的”),因为它基本上是一个蛮力双向 BFS