2017-09-04 108 views
0

如何遞歸搜索具有相同對象列表的對象,並在找到特定對象時將其中斷。如何在也包含對象列表的對象列表上執行DFS

例如,這是我的對象,每個對象可以用列表去深入自己的

MyObject: 

List<MyObject> 
    MyObject <- 2) Tag this and move onto next object 
     List<MyObject> 
      MyObject 
       List<MyObject> 
      MyObject <- 1) BOOM found what I want 
       List<MyObject> 
    MyObject 
    MyObject 
    MyObject 
    MyObject 
    MyObject 
    MyObject 
    MyObject 
    MyObject 

我基本上是想做一個DFS我的名單上。我試圖遞歸地做到這一點,但我似乎無法正常退出它。

enter image description here

+0

DFS是一個圖形算法。要將它應用於您的數據,您必須想出一種方法將其視爲圖形來查看它們。我相信這是你的能力。 –

+0

當您爲DFS包含一些代碼時,您會得到更好的響應。 – SomeDude

回答

1

對於您的問題如上所述,該解決方案可以幫助你

private static boolean search(Object object, Object searchingObject) { 
    List<?> al = (ArrayList) object; 
    for (int index = 0; index < al.size(); index++) { 
     if (al.get(index) instanceof List) { 
      if(search(al.get(index), searchingObject)) { 
       return true; 
      } 
     } else { 
      Iterator<Object> itr = (Iterator<Object>) al.iterator(); 
      Object o; 
      while (itr.hasNext()) { 
       o = itr.next(); 
       if (o.equals(searchingObject)) { 
        return true; 
       } 
      } 
     } 
    } 
    return false; 
}  

主要方法爲abve代碼

public static void main(String[] args) { 
    ArrayList<ArrayList> o = new ArrayList<>(); 
    ArrayList<Integer> al = new ArrayList<>(); 
    ArrayList<ArrayList<Integer>> o1 = new ArrayList<>(); 
    al.add(2); 
    al.add(3); 
    al.add(4); 
    o1.add(al); 
    o.add(o1); 
    Integer i = 4;//Object which has to be searched 
    System.out.println(search(o,i));//returning true 
} 
相關問題