Leetcode 2115. 从给定原材料中找到所有可以做出的菜 拓扑排序+hash+模拟

原题链接:Leetcode 2115. 从给定原材料中找到所有可以做出的菜

在这里插入图片描述
在这里插入图片描述

class Solution {
    
    
public:
    vector<string> findAllRecipes(vector<string>& recipes, vector<vector<string>>& ingredients, vector<string>& supplies) {
    
    
        int n=recipes.size();
        unordered_map<string,int> indegree;
        unordered_map<string,vector<string>> adj;
        for(int i=0;i<n;i++)
        {
    
    
            for(auto x:ingredients[i])
            {
    
    
                adj[x].push_back(recipes[i]);
                indegree[recipes[i]]++;
            }
        }
        queue<string> q;
        for(auto x:supplies)
        {
    
    
            if(indegree[x]==0)   q.push(x);
        }
        vector<string> res;
        while(!q.empty())
        {
    
    
            string now=q.front(); 
            q.pop();
            for(auto x:adj[now])
            {
    
    
                indegree[x]--;
                if(indegree[x]==0) 
                {
    
    
                    q.push(x);
                    res.push_back(x);
                }
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_45791939/article/details/128029786