[LeetCode] Evaluate Division (Java)
https://leetcode.com/problems/evaluate-division/description/
입력 : equations[], values[], queries[]
출력 : 모든 queries에 대한 답의 배열. 단, 답을 결정할 수 없는 경우 -1.0 반환
O(V+E)
그래프, dfs
구현
import java.util.*;
class Solution {
class Node {
String key;
double value;
Node(String key, double value) {
this.key = key;
this.value = value;
}
}
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
Map<String, List<Node>> graph = new HashMap<>();
// 그래프 구축
for (int i = 0; i < equations.size(); i++) {
String var1 = equations.get(i).get(0);
String var2 = equations.get(i).get(1);
double value = values[i];
graph.putIfAbsent(var1, new ArrayList<>());
graph.putIfAbsent(var2, new ArrayList<>());
graph.get(var1).add(new Node(var2, value));
graph.get(var2).add(new Node(var1, 1.0 / value));
}
// 쿼리 처리
double[] results = new double[queries.size()];
for (int i = 0; i < queries.size(); i++) {
String var1 = queries.get(i).get(0);
String var2 = queries.get(i).get(1);
if (!graph.containsKey(var1) || !graph.containsKey(var2)) {
results[i] = -1.0;
} else {
Set<String> visited = new HashSet<>();
results[i] = dfs(graph, var1, var2, 1.0, visited);
}
}
return results;
}
private double dfs(Map<String, List<Node>> graph, String start, String end, double product, Set<String> visited) {
if (start.equals(end)) {
return product;
}
visited.add(start);
for (Node neighbor : graph.get(start)) {
if (!visited.contains(neighbor.key)) {
double result = dfs(graph, neighbor.key, end, product * neighbor.value, visited);
if (result != -1.0) {
return result;
}
}
}
return -1.0;
}
}