|
| 1 | +package com.fishercoder.solutions.thirdthousand; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.HashSet; |
| 7 | +import java.util.LinkedList; |
| 8 | +import java.util.List; |
| 9 | +import java.util.Map; |
| 10 | +import java.util.Queue; |
| 11 | +import java.util.Set; |
| 12 | + |
| 13 | +public class _2115 { |
| 14 | + public static class Solution1 { |
| 15 | + /** |
| 16 | + * My completely original solution, topological sort template comes in pretty handy. |
| 17 | + */ |
| 18 | + public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, String[] supplies) { |
| 19 | + Set<String> allRecipes = new HashSet<>(); |
| 20 | + Collections.addAll(allRecipes, recipes); |
| 21 | + |
| 22 | + Set<String> allSupplies = new HashSet<>(); |
| 23 | + Collections.addAll(allSupplies, supplies); |
| 24 | + |
| 25 | + Map<String, Integer> indegree = new HashMap<>(); |
| 26 | + Map<String, List<String>> adjList = new HashMap<>(); |
| 27 | + Map<String, List<String>> ingredientMap = new HashMap<>(); |
| 28 | + for (int i = 0; i < ingredients.size(); i++) { |
| 29 | + int dependencyCount = 0; |
| 30 | + for (String ingredient : ingredients.get(i)) { |
| 31 | + if (allRecipes.contains(ingredient)) { |
| 32 | + dependencyCount++; |
| 33 | + List<String> list = adjList.getOrDefault(ingredient, new ArrayList<>()); |
| 34 | + list.add(recipes[i]); |
| 35 | + adjList.put(ingredient, list); |
| 36 | + } |
| 37 | + } |
| 38 | + indegree.put(recipes[i], dependencyCount); |
| 39 | + ingredientMap.put(recipes[i], ingredients.get(i)); |
| 40 | + } |
| 41 | + Queue<String> q = new LinkedList<>(); |
| 42 | + for (Map.Entry<String, Integer> entry : indegree.entrySet()) { |
| 43 | + if (entry.getValue() == 0 && allSupplies.containsAll(ingredientMap.get(entry.getKey()))) { |
| 44 | + q.offer(entry.getKey()); |
| 45 | + } |
| 46 | + } |
| 47 | + List<String> result = new ArrayList<>(); |
| 48 | + while (!q.isEmpty()) { |
| 49 | + String curr = q.poll(); |
| 50 | + result.add(curr); |
| 51 | + for (String neighbor : adjList.getOrDefault(curr, new ArrayList<>())) { |
| 52 | + indegree.put(neighbor, indegree.get(neighbor) - 1); |
| 53 | + if (indegree.get(neighbor) == 0) { |
| 54 | + q.offer(neighbor); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + return result; |
| 59 | + } |
| 60 | + |
| 61 | + } |
| 62 | +} |
0 commit comments