C++ DFS Beats 100%


  • 0
    1
    class Solution {
    private:
        vector<int> elements;
        void dfs(vector<vector<int>> & adj, int start, vector<bool> & visited ){
            if(visited[start]) return;
            if(start == 0) return;
            visited[start] = true;
            elements.push_back(start);
            for(auto n : adj[start] ){
                dfs(adj,n,visited);
            }
        }
    public:
        vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) {
            int n = max(*max_element(pid.begin(), pid.end()), *max_element(ppid.begin(), ppid.end()) )+1;
            
            vector<vector<int>> adj(n, vector<int>());
            
            for(int i = 0; i < ppid.size(); i++){
                adj[ppid[i]].push_back(pid[i]);
            }
            vector<bool> visited(n,false);
            dfs(adj, kill, visited);
            
            return elements;
        }
    };
    

Log in to reply
 

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