我年份咋还是总写成20年,害…
题目
https://leetcode-cn.com/problems/evaluate-division/
方法一:floyd
第一次在leetcode遇到最短路径算法
代码
class Solution {
int INF=Integer.MAX_VALUE;
double[][] road=new double[100][100];
int m,n;
HashMap<String,Integer> map=new HashMap<>();
int map_index=0;
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
m=equations.size();
n=queries.size();
double[] res=new double[n];
//初始化
for(int i=0;i<100;i++){
Arrays.fill(road[i],INF);
}
for(int i=0;i<m;i++){
String a=equations.get(i).get(0);
String b=equations.get(i).get(1);
int aa=transfer(a);
int bb=transfer(b);
road[aa][bb]=values[i];
road[bb][aa]=1/values[i];
road[aa][aa]=1;
road[bb][bb]=1;
}
floyd();
for(int i=0;i<n;i++){
String a=queries.get(i).get(0);
String b=queries.get(i).get(1);
int aa=transfer(a);
int bb=transfer(b);
res[i]=road[aa][bb]==INF?-1.0:road[aa][bb];
}
return res;
}
//floyd求最短路
public void floyd(){
for(int k=0;k<map_index;k++){
for(int i=0;i<map_index;i++){
for(int j=0;j<map_index;j++){
if(road[i][k]!=INF&&road[k][j]!=INF)
road[i][j]=Math.min(road[i][j],road[i][k]*road[k][j]);
}
}
}
}
//将字符串转化为数字
public int transfer(String s){
if(map.containsKey(s)){
return map.get(s);
}
else{
map.put(s,map_index);
map_index++;
return map_index-1;
}
}
}