java—如何对同时包含对象列表的对象列表执行dfs

m1m5dgzv  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(247)

当我在一个对象中找到一个特定的对象时,如何递归地搜索一个有相同对象和中断列表的对象。
示例这是我的对象,每个对象都可以使用自己的列表进行更深入的操作

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。我试过递归地去做,但似乎无法正确地退出。

vmpqdwk3

vmpqdwk31#

对于上面解释的问题,此解决方案可能会对您有所帮助

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
}

相关问题