地铁最优线路算法的求解(三)-深度优先搜索java实现
多的不说,show me the code,先上一段java代码

1 /* 2 * 深度优先算法(DFS)算法生成所有可能路径 3 * startId: 出发站 4 * endId: 到达站 5 * graph: 辅助邻接矩阵,若99站与35站相邻, 6 * 则graph[35][99]=1,graph[99][35]=1 7 * 8 * */ 9 10 public static List<List<Integer>> DFSPrintPossiblePath(int startId, int endId, int[][] graph) { 11 // 所有可能路径 12 List<List<Integer>> pathList = new ArrayList(); 13 14 LinkedList<LinkedList<Integer>> pathPQ = new LinkedList(); 15 LinkedList<Integer> path = new LinkedList<>(); 16 //将起点加入pq,路线加入pathPQ 17 path.add(startId); 18 pathPQ.add(path); 19 20 while (!pathPQ.isEmpty()) { 21 // 线路出队 22 LinkedList<Integer> thisPath = pathPQ.pop(); 23 // 该线路末站 24 int lastStation = thisPath.peekLast(); 25 26 //当前节点是终点,即可返回一条路径 27 if (lastStation == endId) { 28 // System.out.println("一条可能路线:path:"); 29 // for (int statsionIndex : thisPath) { 30 // System.out.println("站点 name:" + stations.get(statsionIndex)); 31 // } 32 pathList.add(thisPath); 33 continue; 34 } 35 36 //节点个数 37 int graphLength = graph.length; 38 //将当前节点相连且未访问的节点遍历 39 for (int i = 0; i < graphLength; i++) { 40 //lastStation的邻接点 41 if (graph[lastStation][i] == 1) { 42 43 // 该path是否已经过 站点 44 boolean isFound = false; 45 for (int staIndex : thisPath) { 46 if (i == staIndex) { 47 //System.out.println("该站点 已经过:" + i); 48 isFound = true; 49 break; 50 } 51 } 52 if(isFound) continue; 53 54 //新建 path 55 LinkedList<Integer> newpath1 = new LinkedList<>(); 56 newpath1.addAll(thisPath); 57 newpath1.addLast(i); 58 59 pathPQ.addLast(newpath1); 60 } 61 62 } 63 } 64 return pathList; 65 }
参考文章
地铁线路最短路径(项目实现)
https://www.cnblogs.com/YuQicode/p/13922754.html
【地铁上的面试题】--基础部分--数据结构与算法--动态规划和贪心算法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步