在深度优先搜索中,每当访问一个节点时,我们必须再次获取其相邻节点之一并为该相邻节点执行此过程。根据此情况,可能存在多个深度优先搜索订单。那么,有没有办法在不应用算法和手动计算的情况下计算图表中不同的DFS订单总数?请尽快给我解决方案..
答案 0 :(得分:1)
你可以通过计算每个级别的节点来做到这一点,并且每次进入下一级别时都要保持乘法。
LinkedList<Node> connections = startNode.connections;
long totalOrders = 1L;
while(!connections.isEmpty()){
LinkedList<Node> newConnections = new LinkedList<>();
List<Integer> conSizes = new LinkedList()<>;
for (Node connection : connections) {
if(!connection.visited){
connection.visited = true;
newConnections.addAll(connection.connections);
totalOrders = totalOrders * factorial(connection.connections.size());
}
}
totalOrders = totalOrders * factorial(connections.size());
connections = newConnections;
}
System.out.println(totalOrders)
public static long factorial(int n) {
long fact = 1; // this will be the result
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}