繁体   English   中英

使用DFS查找两个节点之间的所有可能路径

[英]finding all possible paths between two nodes using DFS

我正在尝试在图表中找到所有可能的所有路径。 当我运行该程序时,我收到一个错误说ArrayIndexOutOfBoundsException。 我在哪里需要修复我的代码来解决此错误

private int v;  
 void printAllPaths(String s, String d) {
     int start=airportsHashMap.get(s).intValue();
        int end=airportsHashMap.get(d).intValue();

        //int DaRoute;
        printPaths(start,end);
 }
 public void printPaths(int s, int d)  
 { 

     boolean[] isVisited = new boolean[v]; 
     ArrayList<Integer> pathList = new ArrayList<>(); 

     //add source to path[] 
     pathList.add(s); 

     //Call recursive utility 
     printAllPathsUtil(s, d, isVisited, pathList); 
 } 

 // A recursive function to print 
 // all paths from 'u' to 'd'. 
 // isVisited[] keeps track of 
 // vertices in current path. 
 // localPathList<> stores actual 
 // vertices in the current path 
 private void printAllPathsUtil(Integer u, Integer d, 
                                 boolean[] isVisited, 
                         List<Integer> localPathList) { 

     // Mark the current node 
     isVisited[u] = true; 

     if (u.equals(d))  
     { 
         System.out.println(localPathList); 
         // if match found then no need to traverse more till depth 
         isVisited[u]= false; 
         return ; 
     } 

     // Recur for all the vertices 
     // adjacent to current vertex 
     for (Integer i :adjListArray[u])  
     { 
         if (!isVisited[i]) 
         { 
             // store current node  
             // in path[] 
             localPathList.add(i); 
             printAllPathsUtil(i, d, isVisited, localPathList); 

             // remove current node 
             // in path[] 
             localPathList.remove(i); 
         } 
     } 

     // Mark the current node 
     isVisited[u] = false; 
 } 

我期望输出看起来像:

EWR和PHL之间的所有路径

EWR IAD ILG PHL EWR IAD PHL EWR PHL

EWR和ILG之间的所有路径

EWR IAD ILG EWR IAD PHL ILG EWR PHL ILG EWR PHL IAD ILG

我认为异常是因为你误用了删除 您应该传递索引而不是“对象”。

 for (Integer i :adjListArray[u])  
 { 
     if (!isVisited[i]) 
     { 
         // store current node  
         // in path[] 
         localPathList.add(i);                 <=== i the 'object'
         printAllPathsUtil(i, d, isVisited, localPathList); 

         // remove current node 
         // in path[] 
         localPathList.remove(i);              <=== i should be 'index' not object
     } 
 } 

你冷酷的样子:

 for (Integer i :adjListArray[u])  
 { 
     if (!isVisited[i]) 
     { 
         // store current node  
         // in path[] 
         localPathList.add(i);
         printAllPathsUtil(i, d, isVisited, localPathList); 

         // remove current node 
         // in path[] 
         localPathList.remove(localPathList.size()-1);
     } 
 } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM