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

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

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

  1. MyObject:
  2. List<MyObject>
  3. MyObject <- 2) Tag this and move onto next object
  4. List<MyObject>
  5. MyObject
  6. List<MyObject>
  7. MyObject <- 1) BOOM found what I want
  8. List<MyObject>
  9. MyObject
  10. MyObject
  11. MyObject
  12. MyObject
  13. MyObject
  14. MyObject
  15. MyObject
  16. MyObject

我基本上想在我的列表上做一个dfs。我试过递归地去做,但似乎无法正确地退出。

vmpqdwk3

vmpqdwk31#

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

  1. private static boolean search(Object object, Object searchingObject) {
  2. List<?> al = (ArrayList) object;
  3. for (int index = 0; index < al.size(); index++) {
  4. if (al.get(index) instanceof List) {
  5. if(search(al.get(index), searchingObject)) {
  6. return true;
  7. }
  8. } else {
  9. Iterator<Object> itr = (Iterator<Object>) al.iterator();
  10. Object o;
  11. while (itr.hasNext()) {
  12. o = itr.next();
  13. if (o.equals(searchingObject)) {
  14. return true;
  15. }
  16. }
  17. }
  18. }
  19. return false;
  20. }

abve代码的主要方法

  1. public static void main(String[] args) {
  2. ArrayList<ArrayList> o = new ArrayList<>();
  3. ArrayList<Integer> al = new ArrayList<>();
  4. ArrayList<ArrayList<Integer>> o1 = new ArrayList<>();
  5. al.add(2);
  6. al.add(3);
  7. al.add(4);
  8. o1.add(al);
  9. o.add(o1);
  10. Integer i = 4;//Object which has to be searched
  11. System.out.println(search(o,i));//returning true
  12. }
展开查看全部

相关问题