Advertisement
lifeiteng

399. Evaluate Division

Feb 13th, 2019
445
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.00 KB | None | 0 0
  1. class Solution {
  2.     public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
  3.         Map<String, Map<String, Double>> map = new HashMap<>();
  4.         for(int i = 0; i < equations.length; i++)
  5.         {
  6.             String[] eq = equations[i];
  7.             double v = values[i];
  8.             String from = eq[0], to = eq[1];
  9.             if(!map.containsKey(from)) map.put(from, new HashMap<>());
  10.             if(!map.containsKey(to)) map.put(to, new HashMap<>());
  11.             map.get(from).put(to, v);
  12.             map.get(from).put(from, 1.0);
  13.             map.get(to).put(from, 1 / v);
  14.             map.get(to).put(to, 1.0);
  15.         }
  16.         double[] re = new double[queries.length];
  17.         for(int i = 0; i < queries.length; i++)
  18.         {
  19.             String[] q = queries[i];
  20.             String from =  q[0], to = q[1];
  21.             re[i] = calc(from, to, map);
  22.         }
  23.         return re;
  24.     }
  25.    
  26.     double calc(String from, String to, Map<String, Map<String, Double>> map)
  27.     {
  28.         if(!map.containsKey(from)) return -1.0;
  29.         if(map.get(from).containsKey(to)) return map.get(from).get(to);
  30.         // if(map.containsKey(to) && map.get(to).containsKey(from)) return 1.0 / map.get(to).get(from);
  31.         Queue<String> q = new LinkedList<>();
  32.         Map<String, Double> fmap = map.get(from);
  33.         q.offer(from);
  34.         Set<String> visited = new HashSet<>();
  35.         while(!q.isEmpty())
  36.         {
  37.             String poll = q.poll();
  38.             System.out.println(poll);
  39.             double val = fmap.get(poll);
  40.             if(poll.equals(to)) return val;
  41.             for(String next : map.get(poll).keySet())
  42.             {
  43.                 // if(fmap.containsKey(next)) continue;
  44.                 double bridge = map.get(poll).get(next);
  45.                 fmap.put(next, val * bridge);
  46.                 if(visited.contains(next)) continue;
  47.                 visited.add(next);
  48.                 q.offer(next);
  49.             }
  50.        }
  51.         return -1.0;
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement