Tag: 广度优先搜索

计算广度优先搜索中遍历的边数?

这是我的bfs算法。 我想存储遍历在字段边缘的边数,但我无法确定将变量放在哪里为每个边添加一个。 我总是得到太长的答案,所以我认为这比简单地增加边缘更难。 应该注意的是,这应该仅计算沿真实路径的边缘,而不是额外的边缘。 public int distance(Vertex x, Vertex y){ Queue search = new LinkedList(); search.add(x); x.visited = true; while(!search.isEmpty()){ Vertex t = search.poll(); if(t == y){ return edges; } for(Vertex n: t.neighbours){ if(!n.visited){ n.visited = true; search.add(n); } } System.out.println(search + ” ” + t); } return edges; } 任何和所有的帮助表示赞赏。 如果您需要更多课程/方法,请告诉我 编辑 import java.util.ArrayList; […]

用Java实现BFS

我是Java的初学者,我需要一些帮助。 我正在尝试实现广度优先搜索算法来解决益智游戏(在Android上解锁我的游戏)。 我完成了GUI,但我坚持使用算法。 到目前为止,我可以计算每个块的可用移动,这些移动应该是根节点的子节点。 每个节点(linkedlist)具有每个块的位置,并且所有节点都存储在Set中。 我现在需要的是将每个节点标记为已访问,因此我不会进入循环。 我会感激任何帮助,如果我误解了任何事情,请纠正我。 提前致谢 :)

Java或C ++中的递归广度优先旅行函数?

这是一个广度优先旅行的java代码: void breadthFirstNonRecursive(){ Queue queue = new java.util.LinkedList(); queue.offer(root); while(!queue.isEmpty()){ Node node = queue.poll(); visit(node); if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } } 是否可以编写递归函数来做同样的事情? 起初,我认为这很容易,所以我出来了: void breadthFirstRecursive(){ Queue q = new LinkedList(); breadthFirst(root, q); } void breadthFirst(Node node, Queue q){ if (node == null) return; q.offer(node); Node n = q.poll(); visit(n); […]

如何实现广度优先搜索到一定深度?

我理解并且可以轻松实现BFS。 我的问题是,我们怎样才能将这个BFS限制在一定深度? 假设,我只需要深入10级。

使用广度优先搜索查找最短路径节点

我正在上面的图表上运行广度优先搜索,以找到从Node 0到Node 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); […]

未加权图的最短路径(最少节点)

我正在尝试构建一个方法,在未加权的图形中返回从一个节点到另一个节点的最短路径。 我考虑过使用Dijkstra,但这似乎有点矫枉过正,因为我只想要一对。 相反,我已经实现了广度优先搜索,但问题是我的返回列表包含一些我不想要的节点 – 如何修改我的代码以实现我的目标? public List getDirections(Node start, Node finish){ List directions = new LinkedList(); Queue q = new LinkedList(); Node current = start; q.add(current); while(!q.isEmpty()){ current = q.remove(); directions.add(current); if (current.equals(finish)){ break; }else{ for(Node node : current.getOutNodes()){ if(!q.contains(node)){ q.add(node); } } } } if (!current.equals(finish)){ System.out.println(“can’t reach destination”); } return directions; }