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<String, Map<String, Double>> graph) {//1.定义bfs队列以及visited标记顶点是否访问过Queue<ArcNode> queue = new LinkedList<>();Set<String> visited = new HashSet<>();//2.bfs队列和visited的初始化,第一个访问的顶点是from,from出发到达from权值为1queue.offer(new ArcNode(from, 1));visited.add(from);//3.bfs算法实现while (!queue.isEmpty()) {ArcNode poll = queue.poll();//3.1遍历当前顶点的所有邻接边for (Map.Entry<String, Double> 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;}//没找到目标节点且当前节点未被访问过就记录新的权值并继续bfsif (!visited.contains(adjVertex)) {visited.add(adjVertex);queue.offer(new ArcNode(adjVertex, newWeight));}}}//4.未找到路径return -1;}public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {//1.有向图的定义,key为起始节点,value为终结点以及对应的权值Map<String, Map<String, Double>> graph = new HashMap<>();//2.有向图的构建for (int i = 0; i < equations.size(); i++) {String from = equations.get(i).get(0);String to = equations.get(i).get(1);double weight = values[i];graph.computeIfAbsent(from, k -> 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 < queries.size(); i++) {List<String> 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;}
}