Equations is given in the format A/b = k, where A and B are variables represented as strings, and K is A real number (f Loating point number). Given some queries,returnThe answers. If The answer does not exist,return-1.0. Example:given a/b = 2.0, b/c = 3.0. Queries Are:a/c =?, b/a =?, a/e =?, a/a =?, x/x =? . return[6.0, 0.5,-1.0, 1.0,-1.0 ]. The input is:vector<pair<string, string>> equations, vector<Double>& values, vector<pair<string, string>> queries, where equations.size () = = Values.size (), and the Valu ES is positive. This represents the equations. Return vector<Double>. According to the example Above:equations= [["A", "B"], ["B", "C"]],values= [2.0, 3.0],queries= [["A", "C"], ["B", "a"], ["A", "E"], ["A", "a"], ["X", "X"] ]. The input is always valid. Assume that evaluating the queries would result in no division by zero and there are no contradiction.
Graph, DFS
(1) Build the map, the key is dividend, the value of also a map whose key is divisor and value is the IT parameter. For example, a / b = 2.0
the map entry is <"a", <"b", 2.0>>
. To make searching and calculation easier, we also put into the b / a = 0.5
map.
(2) For each query, use the DFS to search divisors recursively
1 Public classSolution {2 Public Double[] calcequation (string[][] equations,Double[] values, string[][] queries) {3 Double[] res =New Double[queries.length];4Hashmap<string, hashmap<string, double>> map =NewHashmap<string, Hashmap<string, double>>();5 for(inti=0; i<equations.length; i++) {6string[] equation =Equations[i];7 DoubleValue =Values[i];8 if(!map.containskey (equation[0])) {9Map.put (Equation[0],NewHashmap<string, double>());TenMap.get (Equation[0]). Put (Equation[0], 1.0); One } A if(!map.containskey (equation[1])) { -Map.put (Equation[1],NewHashmap<string, double>()); -Map.get (Equation[1]). Put (Equation[1], 1.0); the } -Map.get (Equation[0]). Put (equation[1], value); -Map.get (Equation[1]). Put (equation[0], 1/value); - } + - for(intj=0; j<queries.length; J + +) { +RES[J] =-1.0;//Initialize ADFS (map, queries[j][0], queries[j][1],NewHashset<string> (), Res, J, 1.0); at } - returnRes; - } - - Public voidDFS (hashmap<string, hashmap<string, double>> map, string src, string dest, Hashset<string> visited,Double[] Res,intIndexDoublepathval) { - if(!map.containskey (src) | |!Map.containskey (dest)) { inRes[index] = 1.0; - return; to } + if(Visited.contains (SRC))return; -hashmap<string, double> SRCNB =map.get (SRC); the if(Srcnb.containskey (dest)) { *Res[index] = Pathval *Srcnb.get (dest); $ return;Panax Notoginseng } - Visited.add (SRC); the for(Map.entry<string, double>Entry:srcNb.entrySet ()) { +String Neibor =Entry.getkey (); ADFS (map, Neibor, dest, visited, res, index, pathval*Entry.getvalue ()); the } + visited.remove (SRC); - } $}
Leetcode:evaluate Division