Clean Java Code


  • 0
    H
    public class Solution {
        
        Set<String> visited = new HashSet<>();
        
        public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
            double[] res = new double[queries.length];
            Map<String, List<Pair>> map = new HashMap<>();
            
            for (int e_i = 0; e_i < equations.length; e_i ++) {
                if (!map.containsKey(equations[e_i][0])) map.put(equations[e_i][0], new ArrayList<Pair>());
                if (!map.containsKey(equations[e_i][1])) map.put(equations[e_i][1], new ArrayList<Pair>());
                List<Pair> list1 = map.get(equations[e_i][0]);
                List<Pair> list2 = map.get(equations[e_i][1]);
                
                list1.add(new Pair(equations[e_i][1], values[e_i]));
                list2.add(new Pair(equations[e_i][0], 1.0 / values[e_i]));
            }
            
            for (int q_i = 0; q_i < queries.length; q_i ++) {
                visited.add(queries[q_i][0]);
                res[q_i] = dfs(map, queries[q_i][0], queries[q_i][1], 1.0);
                visited.remove(queries[q_i][0]);
            }
            
            return res;
        }
        
        private double dfs(Map<String,List<Pair>> map, String node1, String node2, double weight) {
            if (!map.containsKey(node1) || !map.containsKey(node2)) return -1.0;
            if (node1.equals(node2)) return weight;
            
            List<Pair> list = map.get(node1);
            for (int l_i = 0; l_i < list.size(); l_i ++) {
                if (!visited.contains(list.get(l_i).letter)) {
                    visited.add(list.get(l_i).letter);
                    double ans = dfs(map, list.get(l_i).letter, node2, weight * list.get(l_i).weight);
                    visited.remove(list.get(l_i).letter);
                    if (ans != -1.0) return ans;
                }
            }
            
            return -1.0;
        }
        
        class Pair {
            String letter;
            double weight;
            
            public Pair(String letter, double weight) {
                this.letter = letter;
                this.weight = weight;
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.