力扣labuladong一刷day42天图的遍历

力扣labuladong一刷day42天图的遍历

一、797. 所有可能的路径

题目链接:https://leetcode.cn/problems/all-paths-from-source-to-target/
思路:这是一个类似邻接表的形式,行索引为指向起始位置,元素值为被指向位置,图的遍历可以采用深度优先,利用有向进行跳转,跳转到尽头结束递归。当然递归必然伴随着回溯,不能光往list中收集元素,回溯返回时也要记得删除元素。

class Solution {
   
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> list = new ArrayList<>();
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
   
        list.add(0);
        traverse(graph, 0);
        return result;
    }

    void traverse(int[][] graph, int deep) {
   
        if (deep >= graph.length-1) {
   
            result.add(new ArrayList<>(list));
            return;
        }
        for (int i = 0; i < graph[deep].length; i++) {
   
            int temp = graph[deep][i];
            list.add(temp);
            traverse(graph, temp);
            list.remove(list.size()-1);
        }
    }
}

相关推荐

  1. labuladongday42

    2023-12-22 01:44:03       53 阅读
  2. labuladongday45二分判定

    2023-12-22 01:44:03       65 阅读
  3. labuladongday46并查集

    2023-12-22 01:44:03       57 阅读
  4. labuladongday47并查集

    2023-12-22 01:44:03       60 阅读
  5. labuladongday35

    2023-12-22 01:44:03       43 阅读
  6. labuladongday34

    2023-12-22 01:44:03       58 阅读
  7. labuladongday36

    2023-12-22 01:44:03       71 阅读
  8. labuladongday52LRU算法

    2023-12-22 01:44:03       59 阅读
  9. labuladongday53LFU 算法

    2023-12-22 01:44:03       60 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-22 01:44:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-22 01:44:03       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-22 01:44:03       82 阅读
  4. Python语言-面向对象

    2023-12-22 01:44:03       91 阅读

热门阅读

  1. KafKa手动提交问题描述

    2023-12-22 01:44:03       55 阅读
  2. 蓝桥杯-每日刷题-023

    2023-12-22 01:44:03       51 阅读
  3. Linux命令行控制小米电源开关

    2023-12-22 01:44:03       48 阅读
  4. Solidity-5-表达式和控制结构

    2023-12-22 01:44:03       41 阅读
  5. PyQt中的冒号(:)

    2023-12-22 01:44:03       54 阅读
  6. RHCE8 资料整理(十二)

    2023-12-22 01:44:03       62 阅读
  7. Issues about Ubuntu & ROS

    2023-12-22 01:44:03       49 阅读
  8. 【版本管理】git stash用法

    2023-12-22 01:44:03       51 阅读
  9. vue跳转方式

    2023-12-22 01:44:03       62 阅读