Skip to content

Commit 4c90ce5

Browse files
Merge pull request #2704 from tahzeer/patch-3
Create 0399-evaluate-division.cpp
2 parents a54f001 + ce08731 commit 4c90ce5

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Diff for: cpp/0399-evaluate-division.cpp

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
class Solution {
2+
unordered_map<string, vector<pair<string, double>>> graph;
3+
unordered_map<string, bool> visited;
4+
double queryAns;
5+
6+
public:
7+
bool dfs(string startNode, string endNode, double runningProduct){
8+
if(graph.find(startNode) == graph.end() || graph.find(endNode) == graph.end()) {
9+
return false;
10+
}
11+
12+
if(startNode == endNode && graph.find(startNode)!=graph.end()) {
13+
queryAns = runningProduct;
14+
return true;
15+
16+
}
17+
18+
bool tempAns = false;
19+
visited[startNode] = true;
20+
21+
for(int i = 0; i < graph[startNode].size(); i++){
22+
if(!visited[graph[startNode][i].first]){
23+
tempAns = dfs(graph[startNode][i].first, endNode, runningProduct*graph[startNode][i].second);
24+
if(tempAns){
25+
break;
26+
}
27+
}
28+
}
29+
visited[startNode] = false;
30+
31+
return tempAns;
32+
}
33+
34+
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
35+
int n = equations.size(), m = queries.size();
36+
vector<double> ans(m);
37+
38+
for(int i = 0; i < n ; i++){
39+
40+
graph[equations[i][0]].push_back({equations[i][1], values[i]});
41+
graph[equations[i][1]].push_back({equations[i][0], 1/values[i]});
42+
visited[equations[i][0]] = false;
43+
visited[equations[i][1]] = false;
44+
45+
}
46+
47+
for(int i = 0; i < m ; i++){
48+
49+
queryAns = 1;
50+
bool pathFound = dfs(queries[i][0], queries[i][1], 1);
51+
if(pathFound) ans[i] = queryAns;
52+
else ans[i] = -1;
53+
54+
}
55+
return ans;
56+
}
57+
};

0 commit comments

Comments
 (0)