[알고리즘] 6 - PrintTree 문제에 대한 나의 해결책(DFS)
#include <iostream>
#include <vector>
#include <string>
#include <utility>      // std::pair, std::make_pair
#include <unordered_map>
using namespace std;
void DFS(int depth, string key, unordered_map<string, vector<string>> mp){
    if(!mp.count(key))// if key does not exist
        return;
    vector<string> values = mp[key];
    for (int i = 0; i < values.size(); i++){
        for (int j = 0; j < depth; j++)
            cout << "\t";
        cout << values[i] << endl;
        DFS(depth+1, values[i], mp);
    }
}
int main()
{
    vector<pair<string, string>> input;
    input.push_back(make_pair("animal", "mammal"));
    input.push_back(make_pair("animal", "bird"));
    input.push_back(make_pair("lifeform", "animal"));
    input.push_back(make_pair("cat", "lion"));
    input.push_back(make_pair("mammal", "cat"));
    input.push_back(make_pair("animal", "fish"));
    unordered_map<string, vector<string>> mp;
    unordered_map<string, bool> seen;
    for (auto p : input){
        string key = p.first;
        string val = p.second;
        seen[val] = true;
        if(mp.count(key)){
            mp[key].push_back(val);
        } else {
            vector<string> arr = {val};
            mp[key] = arr;
        }
    }
    // Finding the start point (root node)
    // 1. Brute force: Use DFS and count the height
    // 2. If the string ever appeared in the p.second (as a val) then remove from the candidate
    string root = "";
    for (auto m : mp){
        if(!seen.count(m.first)){
            root = m.first;
        }
    }
    cout << root << endl;
    DFS(1, root, mp);
    // Use DFS to print out every child
    // Need to add depth for every vector array
    return 0;
}
                Reference
이 문제에 관하여([알고리즘] 6 - PrintTree 문제에 대한 나의 해결책(DFS)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/_ben/algorithms-6-solution-for-printtree-problem-dfs-5b96텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)