https://leetcode.com/problems/evaluate-division
수식(/) 몇 개 주어지고, 새로운 수식에 대한 답 제시하기
ex)
input: a/b=2.0, b/c=3.0
output: a/c=6.0,a/a=1.0, x/x=-1.0
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 start = equations.get(i).get(0);
String end = equations.get(i).get(1);
graph.putIfAbsent(start, new ArrayList<>());
graph.get(start).add(new Node(end, values[i]));
graph.putIfAbsent(end, new ArrayList<>());
graph.get(end).add(new Node(start, 1.0 / values[i]));
}
double[] answer = new double[queries.size()];
for (int i = 0; i < queries.size(); i++) {
String start = queries.get(i).get(0);
String end = queries.get(i).get(1);
if (!graph.containsKey(start) || !graph.containsKey(end)) {
answer[i] = -1.0;
continue;
}
Set<String> visited = new HashSet<>();
answer[i] = dfs(graph, start, end, 1.0, visited);
}
return answer;
}
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 node : graph.get(start)) {
if (!visited.contains(node.value)) {
double result = dfs(graph, node.value, end, product * node.weight, visited);
if (result != -1) {
return result;
}
}
}
return -1;
}
간선의 방향은 연산(/)의 순서를 나타내고, 간선의 가중치는 연산(/)의 결과를 나타낸다. 경로가 있다면 경로를 따라 누적 곱을 계산하면 된다.
가중치 있는 그래프로 모델링 가능하다. 자료 구조는.. Map<String, List> graph.
Node 클래스에 목적지와 가중치가 들어간다. 재귀하면서 곱해준다.