399. Evaluate Division

这题也是很经典哦。可以用Union Find做,但其实用DFS做更直接。
这就是一个典型的图遍历的问题。每条边都是有weight的。
狗家喜欢考图。这就是常见的图问题。
挺好的

class Solution {
    public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
        Map> graph = new HashMap<>();
        buildGraph(graph, equations, values);
        
        double[] ans = new double[queries.length];
        for (int i = 0; i < queries.length; i++) {
            String a = queries[i][0];
            String b = queries[i][1];
            Double f = dfs(graph, a, b, new HashSet());
            ans[i] = f == null ? -1.0 : f;
        }
        return ans;
    }
    private Double dfs(Map> graph, String a, String target, Set visited) {
        if (visited.contains(a)) return null;
        visited.add(a);
        if (!graph.containsKey(a)) return null;
        if (a.equals(target)) return 1.0;
        
        // search for all the neighbors;
        if (graph.get(a) == null) return null;
        for (Map.Entry entry : graph.get(a).entrySet()) {
            Double ratio = dfs(graph, entry.getKey(), target, visited);
            //if ratio != null return
            if (ratio != null) return ratio * entry.getValue();
        }
        return null;
    }
    private void buildGraph(Map> graph, String[][] equations, double[] values ) {
        for (int i = 0; i < values.length; i++) {
            String a = equations[i][0], b = equations[i][1];
            double v = values[i];
            graph.putIfAbsent(a, new HashMap<>());
            graph.putIfAbsent(b, new HashMap<>());
            graph.get(a).put(b, v);
            graph.get(b).put(a, 1.0 / v );
        }
    }
}

你可能感兴趣的:(399. Evaluate Division)