leetcode399.除法求值 - 详解

以示例1为例子,本题目翻译过来其实就是a->b权值为2,b->a权值为1/2,b->c权值为3,c->b权值为1/3,其实就是有向图疑问,不过a->c的权值计算为a->b和b->c权值的乘积2*3=6

class Solution {
private class ArcNode {
private String adjVertex;
private double weight;
public ArcNode(String adjVertex, double weight) {
this.adjVertex = adjVertex;
this.weight = weight;
}
}
private double bfs(String from, String to, Map> graph) {
//1.定义bfs队列以及visited标记顶点是否访问过
Queue queue = new LinkedList<>();
Set visited = new HashSet<>();
//2.bfs队列和visited的初始化,第一个访问的顶点是from,from出发到达from权值为1
queue.offer(new ArcNode(from, 1));
visited.add(from);
//3.bfs算法实现
while (!queue.isEmpty()) {
ArcNode poll = queue.poll();
//3.1遍历当前顶点的所有邻接边
for (Map.Entry adjEdge : graph.get(poll.adjVertex).entrySet()) {
String adjVertex = adjEdge.getKey();
Double weight = adjEdge.getValue();
double newWeight = weight * poll.weight;//顶点start->adjVertex的权值
//找到目标节点直接返回新权值
if (to.equals(adjVertex)) {
return newWeight;
}
//没找到目标节点且当前节点未被访问过就记录新的权值并继续bfs
if (!visited.contains(adjVertex)) {
visited.add(adjVertex);
queue.offer(new ArcNode(adjVertex, newWeight));
}
}
}
//4.未找到路径
return -1;
}
public double[] calcEquation(List> equations, double[] values, List> queries) {
//1.有向图的定义,key为起始节点,value为终结点以及对应的权值
Map> graph = new HashMap<>();
//2.有向图的构建
for (int i = 0; i  new HashMap<>()).put(to, weight);
graph.computeIfAbsent(to, k -> new HashMap<>()).put(from, 1 / weight);
}
//3.处理每个问题的结果
double[] results = new double[queries.size()];
for (int i = 0; i  query = queries.get(i);
String startVertex = query.get(0);
String endVertex = query.get(1);
//3.1顶点不在图中的结果不存在
if (!graph.containsKey(startVertex) || !graph.containsKey(endVertex)) {
results[i] = -1;
continue;
}
//3.2顶点在图中的进行广度优先遍历
results[i] = bfs(startVertex, endVertex, graph);
}
//4.返回结果
return results;
}
}

posted on 2025-09-07 15:08  ljbguanli  阅读(4)  评论(0)    收藏  举报