邻接矩阵DFS遍历以查找有向图中从x到y的路径数(Java)
邻接矩阵DFS遍历以查找有向图中从x到y的路径数(Java),java,algorithm,depth-first-search,directed-graph,adjacency-matrix,Java,Algorithm,Depth First Search,Directed Graph,Adjacency Matrix,私有堆栈=新堆栈(); 公共int-dfs(int-maxDepth){//路径A-C,最大停止点为'x' int src=0; int dest=2; int i; int countDepth=0; int countpath=0; int元素; stack.add(src); 而(!stack.isEmpty()&&countDepth 0) { 添加(i); 如果(i==dest) countpath++; } i++; } countDepth++; } 返回路径; }
私有堆栈=新堆栈();
公共int-dfs(int-maxDepth){//路径A-C,最大停止点为'x'
int src=0;
int dest=2;
int i;
int countDepth=0;
int countpath=0;
int元素;
stack.add(src);
而(!stack.isEmpty()&&countDepth 0)
{
添加(i);
如果(i==dest)
countpath++;
}
i++;
}
countDepth++;
}
返回路径;
}
这段代码的思想是找出从A点到B点(任意A点和B点)有多少条路径的最大停止次数为“x”。因此,从C到C,最多3次停车,有两种可能性:
C->D->C(2站)
C->D->E->C(3站)
从A到C,最多3次停车,有3种可能性:
A->B->C(2站)
A->D->C(2站)
A->E->B->C(3站)
但是,它只找到一个,程序就停止了。这是因为我的countDepth变量。它在
depth>maxDepth
时停止。换句话说,它并没有像我希望的那样遍历我的图,它沿着一个分支向下移动,然后程序停止。如何正确跟踪当前的深度?谢谢大家! 每次从堆栈中弹出某个内容时,您都在增加深度,请注意,您从来没有减少它。因此,for循环将只执行gSize
次
但在深度优先搜索过程中,一旦到达路径的末端(最大长度或死端),就需要返回树,并且深度需要减小
我建议的方法是在堆栈中存储节点和深度
因此,首先将(src,0)
推到堆栈上
然后从堆栈中弹出
(node,i)
,如果i
,则将(child,i+1)
推到堆栈中节点的每个子节点的。如果node==dest
,则在您的计数中添加一个。实际上,通过这种方式可以更简单、更有效地解决此问题:
int count = -1;
Map<Integer , Integer> nodes = new HashMap<>();
nodes.put(src , 1);
//count the depth at which the algorithm currently is
for(int i = 0 ; i < maxDepth ; i++){
Map<Integer , Integer> next_nodes = new HashMap<>();
nodes.stream.forEach(e -> {
if(e.getKey() == dest)
count += e.getValue();
for(int j = 0 ; j < arr[e.getKey()].length ; j++)
if(arr[e.getKey()][j] > 0)
if(next_nodes.containsKey(j))
next_nodes.put(j , next_nodes.get(j) + e.getValue());
else
next_nodes.put(j , e.getValue());
});
nodes = next_nodes;
}
int count=-1;
映射节点=新的HashMap();
nodes.put(src,1);
//计算算法当前所在的深度
对于(int i=0;i{
如果(例如getKey()==dest)
count+=e.getValue();
for(int j=0;j0)
if(下一个节点。containsKey(j))
next_nodes.put(j,next_nodes.get(j)+e.getValue());
其他的
next_nodes.put(j,e.getValue());
});
节点=下一个节点;
}
这背后的基本思想是计算在n
步骤之后,我们可以在每个节点结束的次数。这将每个深度所需的步数减少到最大numberOfNodes
,这比代码中步数的增长(~指数)要好得多
int count = -1;
Map<Integer , Integer> nodes = new HashMap<>();
nodes.put(src , 1);
//count the depth at which the algorithm currently is
for(int i = 0 ; i < maxDepth ; i++){
Map<Integer , Integer> next_nodes = new HashMap<>();
nodes.stream.forEach(e -> {
if(e.getKey() == dest)
count += e.getValue();
for(int j = 0 ; j < arr[e.getKey()].length ; j++)
if(arr[e.getKey()][j] > 0)
if(next_nodes.containsKey(j))
next_nodes.put(j , next_nodes.get(j) + e.getValue());
else
next_nodes.put(j , e.getValue());
});
nodes = next_nodes;
}