【leetcode】399. Evaluate Division

提交代码
class Solution {
    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
    	String start, end;
    	Map<String, Map<String, Double>> graph=new HashMap<>();
    	
    	
    	for(int i=0;i<equations.size();i++) {
    		start = equations.get(i).get(0);
    		end = equations.get(i).get(1);
    		if(graph.containsKey(start)) {
    			graph.get(start).put(end, values[i]);
    		}else {
    			Map<String, Double> path=new HashMap<>();
    			path.put(end, values[i]);
    			graph.put(start, path);
    		}
    		
    		if(graph.containsKey(end)) {
    			graph.get(end).put(start, 1/values[i]);
    		}else {
    			Map<String, Double> path=new HashMap<>();
    			path.put(start, 1/values[i]);
    			graph.put(end, path);
    		}
    	}
    	
    	Map<String, Boolean> visited = new HashMap<>();
    	for(String node: graph.keySet())
    		visited.put(node, false);

    	double[] res=new double[queries.size()];
        for(int i=0;i<queries.size();i++) {
        	start = queries.get(i).get(0);
        	end = queries.get(i).get(1);
        
        	visited.put(start, true);
        	visited.put(end, true);
        	res[i] = findPath(start, end, graph, visited);
        	visited.put(start, false);
        	visited.put(end, false);
        }
        
        return res;
    }
    
    private double findPath(String start, String end, Map<String, Map<String, Double>> graph, Map<String, Boolean> visited) {
    	if(!graph.containsKey(start)||!graph.containsKey(end))	return -1;
    	if(graph.containsKey(start)&&graph.get(start).containsKey(end))	
    		return graph.get(start).get(end);
    	
    	double path = -1;
    	for(String curNode : graph.keySet()) {
    		if(visited.get(curNode))	continue;
    		if(!graph.get(start).containsKey(curNode))	continue;
    		
    		visited.put(curNode, true);
    		path = findPath(curNode, end, graph, visited);
    		visited.put(curNode, false);
    		if(path != -1) {
    			path = graph.get(start).get(curNode)*path;
    			break;
    		}
    	}
    	
    	return path;
    }
}
运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值