【问题标题】:How to do a DFS on a list of objects which also contains a list of objects如何对还包含对象列表的对象列表进行 DFS
【发布时间】:2018-02-12 23:21:04
【问题描述】:

如何递归搜索具有相同对象列表的对象,并在其中找到特定对象时中断。

例如这是我的对象,每个对象都可以更深入地列出自己的列表

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。我尝试递归执行此操作,但似乎无法正确退出。

【问题讨论】:

  • DFS 是一种图算法。要将其应用于您的数据,您必须想出一种将它们作为图表查看的方法。我相信这在你的能力范围内。
  • 当您为 DFS 添加一些代码时,您会得到更好的响应。

标签: java list algorithm search depth-first-search


【解决方案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;
}     

上面代码的主要方法

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    相关资源
    最近更新 更多