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 
} 
相关问题