Untitled
unknown
plain_text
a year ago
2.3 kB
13
Indexable
class Solution {
class Triple {
String destination;
double weight;
public Triple(String d, double w) {
this.destination = d;
this.weight = w;
}
}
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
HashMap<String, List<Triple>> adjList = new HashMap<>();
for (int i = 0; i < equations.size(); i++) {
String s1 = equations.get(i).get(0);
String s2 = equations.get(i).get(1);
double val = values[i];
List<Triple> sourceNode = adjList.getOrDefault(s1, new ArrayList<Triple>());
sourceNode.add(new Triple(s2, val));
adjList.put(s1, sourceNode);
double reverseVal = 1.0/val;
List<Triple> destNode = adjList.getOrDefault(s2, new ArrayList<Triple>());
destNode.add(new Triple(s1, reverseVal));
adjList.put(s2, destNode);
}
double[] result = new double[queries.size()];
int i = 0;
for (List<String> list : queries) {
String s = list.get(0);
String d = list.get(1);
if (!adjList.containsKey(s) || !adjList.containsKey(d)) {
result[i] = -1.00;
i++;
continue;
}
if (s.equals(d)) {
result[i] = 1.00;
i++;
continue;
}
Set<String> visited = new HashSet<>();
result[i] = dfs(s, d, adjList, visited);
i++;
}
return result;
}
private double dfs(String source, String dest, HashMap<String, List<Triple>> adjList, Set<String> visited) {
visited.add(source);
double sum = -1;
for (Triple t : adjList.get(source)) {
if (visited.contains(t.destination)) {
continue;
}
if (t.destination.equals(dest)) {
return t.weight;
}
double val = dfs(t.destination, dest, adjList, visited);
if (val >= 0) {
sum = t.weight * val;
}
}
return sum;
}
}Editor is loading...
Leave a Comment