My code that runs perfectly in eclipse gives wrong output on leetcode


  • 0
    S
      private class Edge
      {
          double weight;
          String start;
          String dest;
          
          public Edge(double weight, String start, String dest)
          {
              this.weight = weight;
              this.start  = start;
              this.dest = dest;
          }
      }
      public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
          Map<String, List<Edge>> adjList = new HashMap<String, List<Edge>>();
          for (int row = 0; row < equations.length; row++)
          {
             List<Edge> list0;
             if (adjList.containsKey(equations[row][0]))
             {
                list0 = adjList.get(equations[row][0]);
             }
             else
             {
                 list0 = new ArrayList<Edge>();
             }
             list0.add(new Edge(values[row],equations[row][0], equations[row][1]));
             adjList.put(equations[row][0], list0);
             List<Edge> list1;
             if (adjList.containsKey(equations[row][1]))
             {
                list1 = adjList.get(equations[row][1]);
             }
             else
             {
                 list1 = new ArrayList<Edge>();
             }
              list1.add(new Edge(1/values[row],equations[row][1], equations[row][0]));
              adjList.put(equations[row][1], list1);
          }
          double[] result = new double[queries.length];
          for( int row = 0; row < queries.length; row++ )
          {
              result[row] = calcQuery(adjList, queries[row][0], queries[row][1]);
          }
          return result;
      }
      
      public double calcQuery(Map<String, List<Edge>> adjList, String start, String end)
      {
          if(!adjList.containsKey(start))
          {
            return -1.0;
          }
          Queue<String> bfs = new LinkedList<String>();
          Queue<Double> calc = new LinkedList<Double>();
          bfs.offer(start);
          Set<String> visited = new HashSet<String>();
          calc.offer(1.0);
          while(!bfs.isEmpty())
          {
              String node = bfs.poll();
              double val = calc.poll();
              if (node == end)
              {
                  return val;
              }
              visited.add(node);
              List<Edge> edges = adjList.get(node);
              if(edges != null)
              {
                for(Edge edge: edges)
                {
                  if (!visited.contains(edge.dest))
                  {
                      bfs.add(edge.dest);
                      calc.add(val*edge.weight);
                  }
                } 
              }
    
          }
          return -1;
      }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.