BFS并通过邻接矩阵找到最短路径
我正在尝试实现BFS并通过邻接矩阵找到最短的路径。但是BF几乎总是返回错误的结果。我在做什么错?
private static bool BFS(int[,] adj, int src, int dest, int v, int[] pred, int[] dist)
{
Queue<int> queue = new Queue<int>();
bool[] visited = new bool[v];
for (int i = 0; i < v; i++)
{
visited[i] = false;
dist[i] = int.MaxValue;
pred[i] = -1;
}
visited[src] = true;
dist[src] = 0;
queue.Enqueue(src);
while (queue.Count != 0)
{
int u= queue.Dequeue();
for (int i = 0; i < adj.GetLength(0); i++)
{
if (visited[i] == false && adj[u,i]!=0)
{
visited[i] = true;
dist[i] = dist[u] + 1;
pred[i] = u;
queue.Enqueue(i);
// stopping condition (when we
// find our destination)
if (i == dest)
return true;
}
visited[u] = true;
}
}
return false;
}
}
I'm trying to implement BFS and finding the shortest path through an adjacency matrix. But BFS almost always returns the result of false. What am I doing wrong?
private static bool BFS(int[,] adj, int src, int dest, int v, int[] pred, int[] dist)
{
Queue<int> queue = new Queue<int>();
bool[] visited = new bool[v];
for (int i = 0; i < v; i++)
{
visited[i] = false;
dist[i] = int.MaxValue;
pred[i] = -1;
}
visited[src] = true;
dist[src] = 0;
queue.Enqueue(src);
while (queue.Count != 0)
{
int u= queue.Dequeue();
for (int i = 0; i < adj.GetLength(0); i++)
{
if (visited[i] == false && adj[u,i]!=0)
{
visited[i] = true;
dist[i] = dist[u] + 1;
pred[i] = u;
queue.Enqueue(i);
// stopping condition (when we
// find our destination)
if (i == dest)
return true;
}
visited[u] = true;
}
}
return false;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这对我来说很奇怪。应该不是:
This looks wierd to me. Should it not be: