LeetCode 399:除法求值(图的bfs遍历)

题目

给你一个变量对数组 equations 和一个实数值数组 values 作为已知条件,其中 equations[i] = [Ai, Bi] 和 values[i] 共同表示等式 Ai / Bi = values[i] 。每个 Ai 或 Bi 是一个表示单个变量的字符串。

另有一些以数组 queries 表示的问题,其中 queries[j] = [Cj, Dj] 表示第 j 个问题,请你根据已知条件找出 Cj / Dj = ? 的结果作为答案。

返回 所有问题的答案 。如果存在某个无法确定的答案,则用 -1.0 替代这个答案。如果问题中出现了给定的已知条件中没有出现的字符串,也需要用 -1.0 替代这个答案。

注意:输入总是有效的。你可以假设除法运算中不会出现除数为 0 的情况,且不存在任何矛盾的结果。

注意:未在等式列表中出现的变量是未定义的,因此无法确定它们的答案。

示例 1:

输入:equations = [[“a”,“b”],[“b”,“c”]], values = [2.0,3.0], queries = [[“a”,“c”],[“b”,“a”],[“a”,“e”],[“a”,“a”],[“x”,“x”]]
输出:[6.00000,0.50000,-1.00000,1.00000,-1.00000]
解释:
条件:a / b = 2.0, b / c = 3.0
问题:a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
结果:[6.0, 0.5, -1.0, 1.0, -1.0 ]
注意:x 是未定义的 => -1.0
示例 2:

输入:equations = [[“a”,“b”],[“b”,“c”],[“bc”,“cd”]], values = [1.5,2.5,5.0], queries = [[“a”,“c”],[“c”,“b”],[“bc”,“cd”],[“cd”,“bc”]]
输出:[3.75000,0.40000,5.00000,0.20000]
示例 3:

输入:equations = [[“a”,“b”]], values = [0.5], queries = [[“a”,“b”],[“b”,“a”],[“a”,“c”],[“x”,“y”]]
输出:[0.50000,2.00000,-1.00000,-1.00000]

提示:

1 <= equations.length <= 20
equations[i].length == 2
1 <= Ai.length, Bi.length <= 5
values.length == equations.length
0.0 < values[i] <= 20.0
1 <= queries.length <= 20
queries[i].length == 2
1 <= Cj.length, Dj.length <= 5
Ai, Bi, Cj, Dj 由小写英文字母与数字组成

思路

一个带权值的无向图。就是求给两个节点,看能否在图中由一个节点遍历到另一个节点,可以的话边的权值的乘积就是答案。

代码

class Solution {
    public class Graph{
        public HashMap<String,Node> nodes;
        public HashSet<Edge> edges;
        public Graph(){
            nodes = new HashMap<>();
            edges = new HashSet<>();
        }
    }
    public class Node{
        public String value;
        public int in;
        public int out;
        public ArrayList<Node> nexts;
        public ArrayList<Edge> edges;
        public Node(String value){
            this.value = value;
            in = 0;
            out = 0;
            nexts = new ArrayList<>();
            edges = new ArrayList<>();
        }
    }
    public class Edge{
        public double weight;
        public Node from;
        public Node to;
        public Edge(double weight, Node from, Node to){
            this.weight = weight;
            this.from = from;
            this.to = to;
        }
    }
    
    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
        ArrayList<Double> ans = new ArrayList<>();
        //1.构建双向图
        Graph graph = createGraph(equations,values);
        // HashMap<String,Node> nodes= graph.nodes;
        //2.遍历双向图的节点,找是否出现变量
        for(int i=0;i<queries.size();i++){
            String startVal = queries.get(i).get(0);
            String endVal = queries.get(i).get(1);
            double distance = 0;
            if(graph.nodes.containsKey(startVal)&&graph.nodes.containsKey(endVal)){
                Node fromNode = graph.nodes.get(startVal);
                Node toNode = graph.nodes.get(endVal);
                HashSet<Node> vis = new HashSet<>();
                ans.add(bfs(fromNode,toNode,vis));
            }else{
                ans.add(-1.0);
            }
        }
        double[] finall = new double[ans.size()];
        for(int i=0;i<ans.size();i++){
            finall[i]=ans.get(i);
        }
        return finall;
    }
    public double bfs(Node fromNode,Node toNode,HashSet<Node> vis){
        if(fromNode==toNode) return 1.0;
        vis.add(fromNode);
        for(Edge nextEdge: fromNode.edges){
            Node nextNode = nextEdge.to;
            if(!vis.contains(nextNode)){
                double distance = nextEdge.weight;
                double res = bfs(nextNode,toNode,vis);
                if(res!=-1.0) return distance*res;
            }
            
        }
        return -1.0;
    }
    public Graph createGraph(List<List<String>> equations,double[] values){
        Graph graph = new Graph();
        for(int i=0;i<equations.size();i++){
            String fromVal = equations.get(i).get(0);
            String toVal = equations.get(i).get(1);
            if(!graph.nodes.containsKey(fromVal))graph.nodes.put(fromVal, new Node(fromVal));
            if(!graph.nodes.containsKey(toVal)) graph.nodes.put(toVal, new Node(toVal));
            Node fromNode = graph.nodes.get(fromVal);
            Node toNode = graph.nodes.get(toVal);
            Edge edge = new Edge(values[i], fromNode, toNode);
            fromNode.out++;
            toNode.in++;
            fromNode.nexts.add(toNode);
            fromNode.edges.add(edge);
            graph.edges.add(edge);

            Edge edge1 = new Edge(1/values[i],toNode, fromNode);
            toNode.out++;
            fromNode.in++;
            toNode.nexts.add(fromNode);
            toNode.edges.add(edge1);
            graph.edges.add(edge1);
        }
        
        return graph;
    }
    
}

执行用时分布1ms,击败81.63%使用 Java 的用户。应该不用再优化了

  • 20
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鸡鸭扣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值