[英]Need help getting to nth level of an adjacency matrix (graph) using a breadth-first search (Java)
public int bfs(int maxDepth){
int src = 2;
int dest = 2;
int i;
int depth = 0;
int countPaths = 0;
int element;
queue.add(src);
while(!queue.isEmpty() && depth <= maxDepth)
{
element = queue.remove();
i = 0;
while(i < 5)
{
if(arr[element][i] > 0)
{
queue.add(i);
if(i == dest)
countPaths++;
}
i++;
}
}
queue.clear();
return countPaths;
}
你好!! 给定源和目的地,我需要找到一条路径。 就遍历图表而言,我的BFS算法工作得很好。 我的问题是在我想要的时候停止它。 我拿出了我增加深度的地方,所以我看起来不像是一个完全白痴。 我希望有人能帮帮忙。 基本上我想知道如何跟踪当前的深度。 谢谢!
例:
找到从C到C的路径数,最多3个停靠点。 答案是两条路:
C - > D - > C(2站)
C - > E - > B - > C(3站)
示例2:找到从A到C的路径数,最多3个停靠点。 答案是三条路。
A - > B - > C(2站)
A - > D - > C(2站)
A - > E - > B - > C - >(3站)
由于在执行bfs时每个节点都应与其深度相关联,因此可以创建一个用于存储节点和深度的类(如果要打印路径,则创建父节点):
package stackoverflow;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
public class BFSTest {
public static class BFSNode {
public int node, depth;
public BFSNode parent;
public BFSNode(int node) {
this.node = node;
this.depth = 0;
this.parent = null;
}
public BFSNode(int node, BFSNode parent) {
this.node = node;
this.depth = parent.depth+1;
this.parent = parent;
}
}
ArrayDeque<BFSNode> queue;
int[][] arr;
public BFSTest() {
queue = new ArrayDeque<BFSNode>();
arr = new int[5][5];
arr[0][1] = arr[0][3] = arr[0][4] = 1;
arr[1][2] = 1;
arr[2][3] = arr[2][4] = 1;
arr[3][2] = arr[3][4] = 1;
arr[4][1] = 1;
}
public int bfs(int src, int dest, int maxDepth){
int i;
int countPaths = 0;
BFSNode element;
queue.add(new BFSNode(src));
while(!queue.isEmpty())
{
element = queue.poll();
if (element.depth > maxDepth)
break;
i = 0;
while(i < 5)
{
if(arr[element.node][i] > 0)
{
if(i == dest && element.depth +1 <= maxDepth) {
BFSNode tmp = element;
List<Integer> path = new ArrayList<Integer>();
path.add(dest);
while (tmp != null) {
path.add(tmp.node);
tmp = tmp.parent;
}
for (int j = path.size() - 1; j >= 0; j--) {
System.out.print(path.get(j) + " ");
}
System.out.println();
countPaths++;
}
queue.add(new BFSNode(i, element));
}
i++;
}
}
queue.clear();
return countPaths;
}
public static void main(String[] args) {
BFSTest test = new BFSTest();
System.out.println(test.bfs(2, 2, 3));
System.out.println(test.bfs(0, 2, 3));
}
}
你得到
//src = 2, dest=2
2 3 2 //path 1
2 4 1 2 //path 2
2 //total
//src=0. dest=2
0 1 2 //path 1
0 3 2 //path 2
0 4 1 2 //path 3
3 //total
问:基本上我想知道如何跟踪当前的深度。
一种解决方案是创建一个包含额外字段深度的包装类,正如@svs在他的回答中所解释的那样。 但是,有一个巧妙的技巧,避免创建一个包装类,它很简单:
queue.add(src);
while(!queue.isEmpty())
{
int size = queue.size();
for(int i=0; i<size; i++)
{
.. //do processing for the current depth
}
}
在for
循环中,执行您要对该级别的节点执行的任何操作,包括将新元素放入队列(即深度等于current_depth + 1的节点)。 在for
循环中仅迭代queue.size()
次数将保证只处理当前级别的节点,而while
循环将保证将处理所有级别(或者只是其中一些级别,如果扩展条件以停止环)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.