当前位置: 首页 > news >正文

leetcode797图论-对邻接矩阵和邻接表不同形式进行dfs与bfs遍历方法

给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序

 graph[i] 是一个从节点 i 可以访问的所有节点的列表(即从节点 i 到节点 graph[i][j]存在一条有向边)。

示例 1:

输入:graph = [[1,2],[3],[3],[]]
输出:[[0,1,3],[0,2,3]]
解释:有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 3

本题输入方式为邻接表方式输入

对于邻接表方式解题方法:

1、DFS遍历

2、BFS遍历

DFS遍历实现代码(基于邻接表)

class Solution {
    List<Integer> path=new ArrayList<>();
     List<List<Integer>> result=new ArrayList<>();
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
     
     path.add(0);
     dfs(graph,0);
     return result;
    }
    private void dfs(int[][] graph,int x){
        if(x==graph.length-1){
            result.add(new ArrayList<>(path));
            return;
        }
        for(int i=0;i<graph[x].length;i++){
            path.add(graph[x][i]);
            dfs(graph,graph[x][i]);
            path.remove(path.size()-1);
        }
    }
}

BFS遍历实现代码(基于邻接表)

import java.util.*;

class Solution {
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        List<List<Integer>> result = new ArrayList<>();
        int target = graph.length - 1;
        
        // BFS队列:存储(当前节点,路径)
        Queue<List<Integer>> queue = new LinkedList<>();
        
        // 初始路径:0
        List<Integer> initialPath = new ArrayList<>();
        initialPath.add(0);
        queue.offer(initialPath);
        
        while (!queue.isEmpty()) {
            List<Integer> currentPath = queue.poll();
            int lastNode = currentPath.get(currentPath.size() - 1);
            
            // 到达目标节点
            if (lastNode == target) {
                result.add(new ArrayList<>(currentPath));
                continue;
            }
            
            // 遍历邻接表中的所有邻居
            for (int neighbor : graph[lastNode]) {
                List<Integer> newPath = new ArrayList<>(currentPath); // 复制路径
                newPath.add(neighbor);
                queue.offer(newPath);
            }
        }
        
        return result;
    }
}

图论题目中除了邻接表还有邻接矩阵形式,可以将邻接表转换为邻接矩阵形式更为直观清晰。

邻接矩阵方式解题方法:

1、DFS遍历

2、BFS遍历

DFS遍历实现代码(基于邻接矩阵)

import java.util.*;

class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    int[][] adjacencyMatrix; // 邻接矩阵

    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        // 1. 将邻接表转换为邻接矩阵
        int n = graph.length;
        adjacencyMatrix = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int neighbor : graph[i]) {
                adjacencyMatrix[i][neighbor] = 1; // 标记存在边
            }
        }

        // 2. 从节点0开始DFS
        path.add(0);
        dfs(0, n - 1);
        return result;
    }

    private void dfs(int current, int target) {
        if (current == target) {
            result.add(new ArrayList<>(path)); // 找到一条路径
            return;
        }

        for (int next = 0; next < adjacencyMatrix.length; next++) {
            if (adjacencyMatrix[current][next] == 1) { // 如果存在边
                path.add(next);
                dfs(next, target);
                path.remove(path.size() - 1); // 回溯
            }
        }
    }
}

BFS遍历实现代码(基于邻接矩阵)

import java.util.*;

class Solution {
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        List<List<Integer>> result = new ArrayList<>();
        int n = graph.length;
        
        // 1. 将邻接表转换为邻接矩阵
        int[][] adjacencyMatrix = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int neighbor : graph[i]) {
                adjacencyMatrix[i][neighbor] = 1;
            }
        }
        
        // 2. BFS初始化:队列存储(当前节点,路径)
        Queue<Pair<Integer, List<Integer>>> queue = new LinkedList<>();
        List<Integer> initialPath = new ArrayList<>();
        initialPath.add(0);
        queue.offer(new Pair<>(0, initialPath));
        
        // 3. BFS遍历
        while (!queue.isEmpty()) {
            Pair<Integer, List<Integer>> current = queue.poll();
            int node = current.getKey();
            List<Integer> path = current.getValue();
            
            if (node == n - 1) {
                result.add(new ArrayList<>(path)); // 找到一条路径
                continue;
            }
            
            // 遍历所有邻接节点
            for (int next = 0; next < n; next++) {
                if (adjacencyMatrix[node][next] == 1) {
                    List<Integer> newPath = new ArrayList<>(path); // 复制路径
                    newPath.add(next);
                    queue.offer(new Pair<>(next, newPath));
                }
            }
        }
        
        return result;
    }
    
    // 辅助Pair类(Java 14+可用java.util.Record替代)
    static class Pair<K, V> {
        K key;
        V value;
        Pair(K key, V value) {
            this.key = key;
            this.value = value;
        }
        K getKey() { return key; }
        V getValue() { return value; }
    }
}

 

 

相关文章:

  • 【C++差分数组 树上倍增】P6869 [COCI2019-2020#5] Putovanje|普及+
  • 电影舆情分析可视化平台管理端实现
  • Redisson的RedLock与联锁(MultiLock)的区别
  • 手持式RFID读写器对比固定式读写器的差异优势
  • Mathwork Platform - Matlab Help Center - Concept and Application
  • 前端面试宝典---数据类型
  • Redis基础指令(Windows)
  • 每日一题——AB10 反转链表
  • 电子电气架构 --- 新能源汽车电子电气系统功能需求
  • AI比人脑更强,因为被植入思维模型【51】效率思维模型
  • Conda 环境离线迁移实战:解决生产环境网络限制的高效方案20250409
  • Redis缓存之预热、击穿、穿透、雪崩
  • yolov8几种模型参数model 解读
  • 【MYSQL从入门到精通】数据类型及建表
  • 牛客 小红杀怪
  • 代码随想录算法训练营第十三天
  • FFT DFT 示波器
  • 期权时间价值与隐含波动率怎么选?
  • [特殊字符] 超轻高性能的 Rust HTTP 服务器 —— Hyperlane [特殊字符][特殊字符]
  • VSCode、clangd、mingw 配置与使用
  • 男的做直播网站好/百度推广关键词匹配模式
  • 找人做网站要注意什么/推广联盟平台
  • java做网站教程/百度广告推广收费标准
  • 做网站的电脑配置/游戏优化大师下载安装
  • 乐站_网站建设_自助建站/南宁seo服务优化
  • 直播做网站/百度收录好的免费网站