LeetCode399——除法求值

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/evaluate-division/

题目描述:

LeetCode399——除法求值_第1张图片

知识点:图的深度优先遍历

思路:图的深度优先遍历

本题是一题经典的图论算法,这里的除法运算可以看成是连接两个节点的一条有向边,那么计算结果存在的条件是什么呢?

(1)两个字符串在equations中都出现过

(2)这两个字符串在equations中存在联系,即同属于一个连通分量

首先,利用一个Map将字符串与数字编号一一对应起来

对于图的深度优先遍历,我们选择用一个邻接矩阵graph来存储图的边权值,同时每一次求两点间的距离都初始化一个visited数组来标记哪些节点已经被遍历过。深度优先遍历过程中,求解距离用的不应该是加法,而应该是乘法

时间复杂度是O(n * m),其中n为queries中的查询数,而m指的是由equations生成的节点数。空间复杂度是O(m ^ 2)。

JAVA代码:

public class Solution {

    private Map stringToInteger = new HashMap<>();

    private int index = 0;

    private double[][] graph;

    private boolean[] visited;

    public double[] calcEquation(List> equations, double[] values, List> queries) {
        for (List list : equations) {
            for (String string : list) {
                if (!stringToInteger.containsKey(string)) {
                    stringToInteger.put(string, index++);
                }
            }
        }
        graph = new double[index][index];
        for (int i = 0; i < equations.size(); i++) {
            List list = equations.get(i);
            String string0 = list.get(0), string1 = list.get(1);
            int index1 = stringToInteger.get(string0), index2 = stringToInteger.get(string1);
            graph[index1][index2] = values[i];
            graph[index2][index1] = 1.0 / values[i];
        }
        double[] result = new double[queries.size()];
        Arrays.fill(result, -1.0);
        for (int i = 0; i < result.length; i++) {
            List list = queries.get(i);
            String string0 = list.get(0), string1 = list.get(1);
            if (stringToInteger.containsKey(string0) && stringToInteger.containsKey(string1)) {
                if (string0.equals(string1)) {
                    result[i] = 1.0;
                } else {
                    int index1 = stringToInteger.get(string0), index2 = stringToInteger.get(string1);
                    visited = new boolean[index];
                    double len = 1.0;
                    dfs(index1, index2, len, result, i);
                }
            }
        }
        return result;
    }

    private void dfs(int begin, int end, double len, double[] result, int k) {
        if (graph[begin][end] == 0) {
            visited[begin] = true;
            for (int i = 0; i < index; i++) {
                if (!visited[i] && graph[begin][i] != 0) {
                    dfs(i, end, len * graph[begin][i], result, k);
                }
            }
        } else {
            result[k] = len * graph[begin][end];
        }
    }

}

LeetCode解题报告:

LeetCode399——除法求值_第2张图片

 

你可能感兴趣的:(LeetCode题解,LeetCode,图,深度优先遍历,除法求值)