주어진 항공권을 모두 이용하여 여행경로를 짜려고 합니다. 항상 "ICN" 공항에서 출발합니다.
항공권 정보가 담긴 2차원 배열 tickets가 매개변수로 주어질 때, 방문하는 공항 경로를 배열에 담아 return 하도록 solution 함수를 작성해주세요.
| tickets | return |
|---|---|
| [["ICN", "JFK"], ["HND", "IAD"], ["JFK", "HND"]] | ["ICN", "JFK", "HND", "IAD"] |
| [["ICN", "SFO"], ["ICN", "ATL"], ["SFO", "ATL"], ["ATL", "ICN"], ["ATL","SFO"]] | ["ICN", "ATL", "ICN", "SFO", "ATL", "SFO"] |
O(N^2)의 시간복잡도를 가지지만, 가지치기 기법을 통해 많은 시간을 줄여준다고 생각했고, N이 최대 10,000이기 때문에 알맞은 알고리즘으로 보인다.#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
bool dfs(string start, int n, vector<string>& path,
unordered_map<string, vector<bool>>& visited,
unordered_map<string, vector<string>>& graph) {
if(path.size() == n + 1){
return true;
}
vector<string> end = graph[start];
for(int i = 0; i < end.size(); i++){
if(visited[start][i]) continue;
visited[start][i] = true;
path.push_back(end[i]);
if(dfs(end[i], n, path, visited, graph)){
return true;
}
visited[start][i] = false;
path.pop_back();
}
return false;
}
vector<string> solution(vector<vector<string>> tickets) {
// tickets 인접리스트로 바꾸기
int n = tickets.size();
unordered_map<string, vector<string>> graph;
unordered_map<string, vector<bool>> visited;
for(vector<string>& ticket : tickets){
graph[ticket[0]].push_back(ticket[1]);
visited[ticket[0]].push_back(false);
}
// 알파벳 별로 정렬
for(auto it = graph.begin(); it != graph.end(); it++){
sort(it->second.begin(), it->second.end());
}
vector<string> path;
path.push_back("ICN");
dfs("ICN", n, path, visited, graph);
return path;
}