思路:构建一个图,求x /y 就是求x到y的一条路径
package l399;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
class A {
String den;
double rst;
public A(String den, double rst) {
this.den = den;
this.rst = rst;
}
}
public class Solution {
boolean findPath = false;
double rst = 1;
public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
Map<String, List<A>> m = new HashMap<String, List<A>>();
for(int i=0; i<equations.length; i++) {
String[] s = equations[i];
if(!m.containsKey(s[0])) m.put(s[0], new ArrayList<A>());
m.get(s[0]).add(new A(s[1], values[i]));
if(!m.containsKey(s[1])) m.put(s[1], new ArrayList<A>());
m.get(s[1]).add(new A(s[0], 1.0 / values[i]));
}
double[] ret = new double[queries.length];
Arrays.fill(ret, -1);
for(int i=0; i<queries.length; i++) {
if(!m.keySet().contains(queries[i][0]) || !m.keySet().contains(queries[i][1]))
continue;
rst = 1;
findPath = false;
dfs(m, queries[i][0], queries[i][0], queries[i][1], 1, new HashSet<String>());
if(findPath) ret[i] = rst;
}
return ret;
}
private void dfs(Map<String, List<A>> m, String ori, String s, String t, double cal, HashSet<String> visted) {
if(s.equals(t)) {
findPath = true;
rst = cal;
return;
}
for(A next : m.get(s)) {
if(!visted.contains(next.den)) {
visted.add(next.den);
dfs(m, ori, next.den, t, cal*next.rst, visted);
visted.remove(visted.size()-1);
}
}
}
}