๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ
728x90
๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๐Ÿง‘‍๐Ÿ’ปํ’€์ด ๊ณผ์ •

 

๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ™œ์šฉํ•˜์—ฌ ํ’€์—ˆ์Šต๋‹ˆ๋‹ค. ๋ชฉ์ ์ง€(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
๋ฐ˜์‘ํ˜•