Find all paths with min weights in an undirected graph
Posted 北叶青藤
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Find all paths with min weights in an undirected graph相关的知识,希望对你有一定的参考价值。
You are given a list of edges in a graph with weight. Find all the paths between start node and end node with min weights in the path.
The edges like (node1, node2, weight)
class Solution { int minPathSum = Integer.MAX_VALUE; public List<List<Integer>> allShortestPaths(int[][] edges, int start, int end) { Map<Integer, Map<Integer, Integer>> graph = buildGraph(edges); List<List<Integer>> results = new LinkedList<>(); Set<Integer> visited = new HashSet<>(); dfs(start, end, visited, graph, new LinkedList<>(), results, 0); return results; } private void dfs(int current, int end, Set<Integer> visited, Map<Integer, Map<Integer, Integer>> graph, List<Integer> path, List<List<Integer>> results, int pathSum) { path.add(current); if (current == end) { if (minPathSum > pathSum) { results.clear(); results.add(new LinkedList<>(path)); minPathSum = pathSum; } else if (pathSum == minPathSum) { results.add(new LinkedList<>(path)); } path.remove(path.size() - 1); return; } visited.add(current); for (Map.Entry<Integer, Integer> entry : graph.getOrDefault(current, new HashMap<>()).entrySet()) { if (!visited.contains(entry.getKey())) { dfs(entry.getKey(), end, visited, graph, path, results, pathSum + entry.getValue()); } } path.remove(path.size() - 1); visited.remove(current); } private Map<Integer, Map<Integer, Integer>> buildGraph(int[][] edges) { Map<Integer, Map<Integer, Integer>> graph = new HashMap<>(); for (int[] edge : edges) { graph.putIfAbsent(edge[0], new HashMap<>()); graph.putIfAbsent(edge[1], new HashMap<>()); graph.get(edge[0]).put(edge[1], edge[2]); graph.get(edge[1]).put(edge[0], edge[2]); } return graph; } }
以上是关于Find all paths with min weights in an undirected graph的主要内容,如果未能解决你的问题,请参考以下文章
2017-11 (not fresh grad ) find all substring with N size and only one duplicate character.
No mapping found for HTTP request with URI [/crmcrmcrm/css/bootstrap.min.css] in DispatcherServlet w
442. Find All Duplicates in an Array
[LeetCode] 448.Find All Numbers Disappeared in an Array