本帖最后由 滑铁卢鹅大爷 于 2022-3-10 11:57 编辑
题目是这样:provide了一个adjacency list的weighted graph,然后需要通过backtracking return maximumProduct和他的path。例子如下:g = {
"A": {"B": 6, "D": 1},
"B": {"A": 6, "C": 5, "D": 2, "E": 2},
"D": {"A": 1, "B": 2, "E": 2},
"E": {"B": 2, "C": 5, "D": 2},
"C": {"B": 5, "E": 5}
}
Expected: method getMaximumPathProduct() 应该return 120,variable List<String> path = ["A", "B", "D", "E", "C"]
楼主已经通过backtracking得到了maximumProduct,但是卡在了如何记录path. 代码贴在下面了,请大神们对其做更改,需要能run的code~ 感谢!
PS: 想再问一下时间复杂度以及有没有pruning的可能- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
- public class Test {
- static final String START = "A";
- static final String TARGET = "C";
- List<String> path = new ArrayList<>();
- public static void main(String[] args) {
- Map<String, Map<String, Integer>> graph = getSimplerStaticData();
- System.out.println(getMaximumPathProduct(graph, START, TARGET));
- }
- private static int getMaximumPathProduct(Map<String, Map<String, Integer>> graph, String start, String target) {
- Set<String> seen = new HashSet<>();
- seen.add(start);
- return dfs(start, target, seen, graph, new LinkedList<>());
- }
- private static int dfs(String current, String target, Set<String> seen, Map<String, Map<String, Integer>> graph, List<String> subPath) {
- if(target.equals(current)) {
- return 1;
- }
- int res = 0;
- Map<String, Integer> neighbors = graph.get(current);
- for(String neighbor: neighbors.keySet()) {
- if(!seen.contains(neighbor)) {
- seen.add(neighbor);
- int distance = neighbors.get(neighbor);
- res = Math.max(res, distance * dfs(neighbor, target, seen, graph, subPath));
- seen.remove(neighbor);
- }
- }
- return res;
- }
- private static Map<String, Map<String, Integer>> getSimplerStaticData() {
- Map<String, Map<String, Integer>> res = new HashMap<>();
- Map<String, Integer> value1 = new HashMap<>();
- value1.put("B", 6);
- value1.put("D", 1);
- res.put("A", value1);
- Map<String, Integer> value2 = new HashMap<>();
- value2.put("A", 6);
- value2.put("D", 2);
- value2.put("E", 2);
- value2.put("C", 5);
- res.put("B", value2);
- Map<String, Integer> value3 = new HashMap<>();
- value3.put("B", 5);
- value3.put("E", 5);
- res.put("C", value3);
- Map<String, Integer> value4 = new HashMap<>();
- value4.put("A", 1);
- value4.put("B", 2);
- value4.put("E", 2);
- res.put("D", value4);
- Map<String, Integer> value5 = new HashMap<>();
- value5.put("B", 2);
- value5.put("C", 5);
- value5.put("D", 2);
- res.put("E", value5);
- return res;
- }
- }
复制代码 |