【发布时间】:2010-09-27 01:40:01
【问题描述】:
我正在尝试使用 BFS 算法制作一个程序,因此我将每个节点放入队列中,一旦每个级别都在队列中,我开始将其与另一个节点进行比较以查看它们是否相等,但是问题我的问题是我的队列中的元素正在被修改,所以当我执行 Dequeue 时,我从来没有得到答案,而且我遇到了堆栈溢出。
我不确定我的代码的哪一部分有问题,因为堆栈溢出到处都是,但我会发布队列和出队的一部分。
所以是的,基本上在第二个循环之后它开始搞砸一切,它向我的矩阵添加了超过 1 个“b”并修改了我的队列元素。
private void BFS(Nodo<string[,]> nodo)
{
Array.Copy(nodo.getEA(), datos5, 9);
temp = null;
temp2 = null;
temp3 = null;
temp4 = null;
Array.Copy(datos5, datos, 9);
//There are a bunch of if and else if so I just posted one
if (datos[1, 0].Equals("b"))
{
Array.Copy(datos, datos2, 9);
Array.Copy(datos, datos3, 9);
cont3=3;
//UP from 1,0 a 0,0
datos[1, 0] = datos[0, 0];
datos[0, 0] = "b";
temp = new Nodo<string[,]>(datos);
temp.setCamino("U");
temp.setPadre(nodo);
myq.Enqueue(temp);
temp = null;
//Right from 1,0 a 1,1
datos2[1, 0] = datos2[1, 1];
datos2[1, 1] = "b";
temp2 = new Nodo<string[,]>(datos2);
temp2.setCamino("R");
temp2.setPadre(nodo);
myq.Enqueue(temp2);
temp = null;
//Down from 1,0 a 2,0
datos3[1, 0] = datos3[2, 0];
datos3[2, 0] = "b";
temp3 = new Nodo<string[,]>(datos3);
temp3.setCamino("D");
temp3.setPadre(nodo);
myq.Enqueue(temp3);
fila();
}
}
private void fila()
{
Nodo<string[,]> temp5;
for (int i = 0; i < myq.Count; i++)
{
temp5 = null;
temp5 = (Nodo<string[,]>)myq.Dequeue();
if (objetivo(temp5, nodof))
{
if (!flag2)
{
boxResultado.AppendText("Problem solved");
flag2 = true;
break;
}
else
{
break;
}
}
else
{
if (!flag2)
{
BFS(temp5);
}
else
{
break;
}
}
}
}
private bool objetivo(Nodo<string[,]> p, Nodo<string[,]> e)
{
nodo1 = null;
nodo2 = null;
bool flag = false;
nodo1 = p.getEA();
nodo2 = e.getEA();
for (int i = 0; i < 3; i++)
{
for (int f = 0; f < 3; f++)
{
if (nodo1[i, f] != nodo2[i, f])
{
flag = true;
}
}
}
if (flag)
{
return false;
}
else
{
return true;
}
}
我知道我的代码非常糟糕,但在过去 5 个小时左右我一直在试图找出这个问题,所以我一直在到处修改,试图找出问题所在,但我感到非常沮丧所以我决定在这里寻求帮助。 顺便说一句,这是在 C# 中
提前致谢
【问题讨论】: