您的位置:首页 > 其它

Leetcode 329. Longest Increasing Path in a Matrix

2016-12-19 17:37 309 查看

-题目

Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.

Example:

Given a / b = 2.0, b / c = 3.0.

queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .

return [6.0, 0.5, -1.0, 1.0, -1.0 ].

The input is:

vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector<double>.


-思路

简单的思路就是对每一个查询进行一次搜索,如果是在邻接矩阵中已经直接给出的值,那么我们可以返回这个值,如果是要通过几个基本元素的乘积来得出结果,那么用dfs算法来判断是否可以构成查询的这个元素。

要注意的是需要判断查询的元素是否存在于图中,也即x / x返回-1而不是1.

-代码

class Solution {
public:
vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
//已经确定输入合法
vector<double> result(queries.size());
if(equations.size() != values.size()) return result;

set<string> nodes;
map<string, int> node2index;
for(int i = 0; i < equations.size(); i++) {
nodes.insert(equations[i].first);
nodes.insert(equations[i].second);
}
int n = nodes.size();
vector<vector<double> > Adjmatrix(n, vector<double>(n, 0));
int index = 0;
set<string>::iterator it;
for(it = nodes.begin(); it != nodes.end(); it++) {
node2index[*it] = index++;
}
for(int i = 0; i < values.size(); i++) {
Adjmatrix[node2index[equations[i].first]][node2index[equations[i].second]] = values[i];
Adjmatrix[node2index[equations[i].second]][node2index[equations[i].first]] = 1 / values[i];
Adjmatrix[node2index[equations[i].first]][node2index[equations[i].first]] = 1;
Adjmatrix[node2index[equations[i].second]][node2index[equations[i].second]] = 1;
}
//构建初步的邻接图矩阵 用DFS求传递闭包
for(int i = 0; i < queries.size(); i++) {
//排除一些奇怪的情况
if((node2index.find(queries[i].first) == node2index.end()) || (node2index.find(queries[i].second) == node2index.end())) {

result[i] = -1;
continue;
}
if(queries[i].first == queries[i].second) {
result[i] = 1;
continue;
}
//如果不是直接可预知的 通过DFS来找到它的值
vector<bool> isVisited(n, 0);
result[i] = dfs(node2index[queries[i].first], node2index[queries[i].second], 1, isVisited, Adjmatrix);
}

return result;
}
double dfs(int s, int t, double res, vector<bool> isVisited, vector<vector<double> > Adjmatrix) {
if(!isVisited[s]) {
//如果没有访问过当前结点
//访问当前结点
isVisited[s] = 1;
//如果从s有到目标结点的路径返回
if(Adjmatrix[s][t] != 0) {
return res * Adjmatrix[s][t];
}
else {
for(int i = 0; i < Adjmatrix[s].size(); i++) {
if(Adjmatrix[s][i] != 0) {
double cres = dfs(i, t, res*Adjmatrix[s][i], isVisited, Adjmatrix);
if(cres != -1) return cres;
}
}
}
}
return -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode