๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(Programmers)

[c++] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์—ฌํ–‰๊ฒฝ๋กœ(Level 3)

by ์•ˆ์ฃผํ˜• 2022. 5. 27.

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์—ฌํ–‰๊ฒฝ๋กœ

[["ICN", "SFO"], ["ICN", "ATL"], ["SFO", "ATL"], ["ATL", "ICN"], ["ATL","SFO"]] ["ICN", "ATL", "ICN", "SFO", "ATL", "SFO"]

programmers.co.kr

 

์ฝ”๋“œ

#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <iostream>

using namespace std;

struct Info{
    string city;
    int index;
};

unordered_map<string, vector<Info>>graph;
bool flag = true;
vector<string>answer;
int visited[10001];

void dfs(string now, int move, vector<string>memory, int len){
    if(move == len&&flag){
        flag = false;
        answer = memory;
        return;
    }
    
    for(int i=0; i<graph[now].size(); i++){
        if(visited[graph[now][i].index]) continue;
        visited[graph[now][i].index] = 1;
        memory.push_back(graph[now][i].city);
        dfs(graph[now][i].city, move+1, memory, len);
        memory.pop_back();
        visited[graph[now][i].index] = 0;
    }
}
vector<string> solution(vector<vector<string>> tickets) {
    sort(tickets.begin(), tickets.end());
    
    for(int i=0; i<tickets.size(); i++){
        string a = tickets[i][0];
        string b = tickets[i][1];
        graph[a].push_back({b,i});
    }
    
    dfs("ICN", 0, {"ICN"}, tickets.size());
    
    return answer;
}

 

ํ’€์ด

๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ž…๋ ฅ์„ ์กฐ์‹ฌํ•ด์•ผ ํ•˜๋Š”๋ฐ {{"ICN","AAA"},{"ICN","AAA"},{"ICN","AAA"},{"AAA","ICN"},{"AAA","ICN"}} ์™€ ๊ฐ™์ด ์ค‘๋ณต๋œ ํ‹ฐ์ผ“์ด ์žˆ์„ ๋•Œ ์ฒ˜๋ฆฌ๋ฅผ ์ž˜ํ•ด์ฃผ์ง€ ์•Š์œผ๋ฉด ์ฑ„์  ๋ฐ์ดํ„ฐ 1๋ฒˆ์—์„œ ๊ณ„์† ํ‹€๋ฆฌ๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

๊ท€์ฐฎ์•„์„œ ์•ˆํ’€๋˜๊ฑธ ํ•œ ๋ฒˆ์— ์‹น ํ’€์–ด๋ฒ„๋ฆฌ๋‹ˆ ์† ์‹œ์›ํ•˜๋„ค์š”

๋Œ“๊ธ€