일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
Tags
- LeetCode
- 파이썬
- iterator
- 109. Convert Sorted List to Binary Search Tree
- Generator
- Class
- 운영체제
- Python Implementation
- 30. Substring with Concatenation of All Words
- Protocol
- concurrency
- Decorator
- 시바견
- Python Code
- 컴퓨터의 구조
- shiba
- attribute
- 밴픽
- Regular Expression
- Substring with Concatenation of All Words
- t1
- 43. Multiply Strings
- 프로그래머스
- DWG
- Convert Sorted List to Binary Search Tree
- data science
- 715. Range Module
- 315. Count of Smaller Numbers After Self
- kaggle
- Python
Archives
- Today
- Total
Scribbling
[Programmers] 여행경로 본문
https://school.programmers.co.kr/learn/courses/30/lessons/43164
1. Python
from collections import defaultdict
def solution(tickets):
tickets.sort()
routes = defaultdict(list)
for u, v in tickets:
routes[u].append(v)
def dfs(u, tickets, path):
if not tickets:
return path
for v in routes[u]:
if [u, v] in tickets:
tickets.remove([u, v])
ret = dfs(v, tickets, path + [v])
if ret is not None:
return ret
tickets.append([u, v])
return dfs("ICN", tickets, ["ICN"])
2. C++
vector<string> dfs(map<string, vector<string>>& routes, string u, vector<vector<string>>& tickets, vector<string> path) {
if (tickets.empty()) return path;
for (string v : routes[u]) {
vector<string> tmp {u, v};
auto it = find(tickets.begin(), tickets.end(), tmp);
if (it != tickets.end()) {
tickets.erase(it);
vector<string> nxt_path {path};
nxt_path.push_back(v);
vector<string> ret = dfs(routes, v, tickets, nxt_path);
if (!ret.empty()) return ret;
tickets.push_back(tmp);
}
}
return vector<string>();
}
vector<string> solution(vector<vector<string>> tickets) {
sort(tickets.begin(), tickets.end());
map<string, vector<string>> routes;
for (auto ticket : tickets) {
if (routes.find(ticket[0]) == routes.end()) {
routes[ticket[0]] = vector<string> {ticket[1]};
}
else {
routes[ticket[0]].push_back(ticket[1]);
}
}
return dfs(routes, "ICN", tickets, {"ICN"});
}
'Computer Science > Algorithms & Data Structures' 카테고리의 다른 글
[Programmers] 입국심사 (0) | 2024.06.27 |
---|---|
[Programmers] 징검다리 (0) | 2024.06.27 |
[Programmers] 아이템 줍기 (0) | 2024.06.21 |
[Programmers] 단어 변환 (0) | 2024.06.20 |
[Programmers] 게임 맵 최단거리 (0) | 2024.06.20 |