728x90
๐๋ฌธ์ ๋ณด๋ฌ๊ฐ๊ธฐ
๐ง๐ปํ์ด ๊ณผ์
๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ ํ์ฉํ์ฌ ํ์์ต๋๋ค. ๋ชฉ์ ์ง(Destination)๋ฅผ ์์์ ์ผ๋ก ํ์ฌ ๊ฐ ์ง์ญ์ ๋ํ ์ต๋จ ๊ฑฐ๋ฆฌ ๋ฐฐ์ด์ ๊ตฌํ๊ณ , ์ถ๋ฐ์ง(source)๋ค์ ํด๋นํ๋ ๊ฐ๋ค์ answer ๋ฐฐ์ด์ ๋ด์์ฃผ์์ต๋๋ค.
๋ง์ฝ ์ด๋ค ์ถ๋ฐ์ง์ ์ต๋จ ๊ฑฐ๋ฆฌ ๊ฐ์ด ์ด๊น๊ฐ๊ณผ ๊ฐ๋ค๋ฉด, ๊ทธ ์ง์ญ์ ๋ชป ๊ฐ๋ค๋ ์๋ฏธ์ด๋ฏ๋ก -1์ ๋ด์์ฃผ๋ฉด ๋๊ตฌ์. ๋ํ, ๋ชจ๋ ์ง์ญ ๊ฐ์ ์ด๋ ๋น์ฉ์ด 1์ด๋ฏ๋ก, ์ฐ์ ์์ ํ ๋์ ์ผ๋ฐ ํ๋ฅผ ํ์ฉํ์ฌ ์๊ฐ์ ์ค์์ต๋๋ค.
โ๏ธ์์ค ์ฝ๋ ๋ฐ ๊ฒฐ๊ณผ
#include <vector>
#include <queue>
#define INF 1000000000
using namespace std;
using Data = pair<int, int>; // <๋น์ฉ, ์ง์ญ>
void Dijkstra(const vector<vector<int>>& routes, vector<int>& distances, int n, int source) {
queue<Data> regions;
distances[source] = 0;
regions.emplace(0, source);
while (!regions.empty()) {
int cost = regions.front().first;
int region = regions.front().second;
regions.pop();
if (cost < distances[region])
continue;
for (const int& nextRegion : routes[region]) {
int nextCost = cost + 1;
if (nextCost < distances[nextRegion]) {
distances[nextRegion] = nextCost;
regions.emplace(nextCost, nextRegion);
}
}
}
}
vector<int> solution(int n, vector<vector<int>> roads, vector<int> sources, int destination) {
vector<vector<int>> routes(n + 1, vector<int>());
for (const vector<int>& road : roads) {
int from = road[0], to = road[1];
routes[from].emplace_back(to);
routes[to].emplace_back(from);
}
vector<int> answer;
vector<int> distances(n + 1, INF);
Dijkstra(routes, distances, n, destination);
for (const auto& source : sources) {
int distance = distances[source] == INF ? -1 : distances[source];
answer.emplace_back(distance);
}
return answer;
}
728x90
๋ฐ์ํ
'๐คAlgorithm > Programmers' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Programmers] Lv3. ํฉ์น ํ์ ์๊ธ | C++ (0) | 2024.01.16 |
---|---|
[Programmers] Lv3. [1์ฐจ] ์ ํ๋ฒ์ค | C++ (0) | 2023.11.18 |
[Programmers] Lv3. ์ฌ ์ฐ๊ฒฐํ๊ธฐ | C++ (1) | 2023.10.22 |
[Programmers] Lv3. ๊ฐ์ฅ ๋จผ ๋ ธ๋ | C++ (0) | 2023.10.22 |
[Programmers] Lv3. [์นด์นด์ค ์ธํด] ๋ณด์ ์ผํ | C++ (0) | 2023.10.22 |