2016-04-29 159 views
0

深度優先搜索,無論何時訪問節點,我們都必須再次取其相鄰節點中的一個,併爲該相鄰節點執行此過程。根據這個,可能會有多個Depth第一個搜索順序。那麼,是否有任何方法可以在不應用算法和手動計算的情況下統計圖中總的不同DFS訂單?請儘快給我解決方案..深度優先搜索指令

回答

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; 
    }