java广度优先求解最短路径_java – 使用广度优先搜索查找最短路径节点

u0mFP.png

我正在上面的图表上运行广度优先搜索,以找到从节点0到节点6的最短路径.

我的代码

public List shortestPathBFS(int startNode, int nodeToBeFound){

boolean shortestPathFound = false;

Queue queue = new LinkedList();

Set visitedNodes = new HashSet();

List shortestPath = new ArrayList();

queue.add(startNode);

shortestPath.add(startNode);

while (!queue.isEmpty()) {

int nextNode = queue.peek();

shortestPathFound = (nextNode == nodeToBeFound) ? true : false;

if(shortestPathFound)break;

visitedNodes.add(nextNode);

System.out.println(queue);

Integer unvisitedNode = this.getUnvisitedNode(nextNode, visitedNodes);

if (unvisitedNode != null) {

queue.add(unvisitedNode);

visitedNodes.add(unvisitedNode);

shortestPath.add(nextNode); //Adding the previous node of the visited node

shortestPathFound = (unvisitedNode == nodeToBeFound) ? true : false;

if(shortestPathFound)break;

} else {

queue.poll();

}

}

return shortestPath;

}

我需要追踪BFS算法的节点.遍历到达节点6,如[0,3,2,5,6].为此我创建了一个名为shortestPath&的List.尝试存储受访节点的先前节点,以获取节点列表. Referred

但它似乎没有用.最短路径为[0,3,2,5,6]

在列表中我得到的是最短路径:[0,0,0,0,1,3,3,2,5]

它部分正确,但额外1.

如果我再次从shortestPath列表的第一个元素0开始&开始遍历&回溯.像1没有边缘到3,所以我回溯&从0到3到5,我会得到答案但不确定这是否正确.

获取最短路径节点的理想方法是什么?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值