java 查找图片所在位置,如何从图的广度优先搜索中获取路径中的所有节点

假设我们有一个这样的简单图:

hlQBi.jpg

通过深度优先搜索很容易找到从起始节点到结束节点的路径,但是在尝试使用广度优先搜索执行相同操作时遇到了困难 . 我的代码如下:

public List getPathBreadth(String name1, String name2) {

Node node1 = getNode(name1);

Node node2 = getNode(name2);

if (node1 == null || node2 == null) {

return null;

}

return getPathBreadth(node1, node2, new HashSet(), new LinkedList());

}

private List getPathBreadth(Node start, Node destination, HashSet visited, Queue queue) {

List path = new ArrayList();

if (start == destination) {

path.add(start.name);

return path;

}

visited.add(start.name);

queue.offer(start);

while (queue.size() > 0) {

Node cur = queue.poll();

for (String friend : cur.friends) {

if (visited.contains(friend)) {

continue;

}

visited.add(friend);

if (getNode(friend) == destination) {

path.add(friend); // I got the final node, I could also add cur, but how do I get the previous nodes along the path

return path;

}

queue.offer(getNode(friend));

}

}

return path;

}

假设我们想要从 John 转到 Linda ,所以我希望返回类似 [Linda, Robert, John] 或 [Linda, Patrica, John] 的内容,但我现在能做的最好的事情是得到最后一个节点的最后一个和第二个节点 . 在这种情况下,它们是 Linda 和 Robert . 如何获取路径中的所有先前节点?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值