๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/Leetcode

[Leetcode,c++] Network Delay Time

by dkswnkk 2021. 11. 22.

๋ฌธ์ œ

 

Network Delay Time - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

์ฝ”๋“œ

class Solution {
public:
    vector<pair<int,int>>graph[101];
    int d[101];
    
    void dijkstra(int start){
        priority_queue<pair<int,int>>pq;
        pq.push({0,start});
        d[start]=0;
        
        while(!pq.empty()){
            int dist = -pq.top().first;
            int now  = pq.top().second;
            pq.pop();
            if(d[now]<dist) continue;
            
            for(int i=0; i<graph[now].size(); i++){
                int cost = dist + graph[now][i].second;
                int neighbor = graph[now][i].first;
                if(cost<d[neighbor]){
                    d[neighbor] = cost;
                    pq.push({-cost,neighbor});
                }
            }
        }
    }
    
    int networkDelayTime(vector<vector<int>>& times, int n, int k) {
        for(int i=0; i<times.size(); i++){
            graph[times[i][0]].push_back({times[i][1],times[i][2]});
        }
        
        fill(d,d+101,1e9);
        
        dijkstra(k);
        
        int ans=0;
        
        for(int i=1; i<=n; i++){
            if(d[i]==1e9) return -1;
            else ans=max(ans,d[i]);
        }
        
        return ans;
    }
    
};

 

ํ’€์ด

dijkstra๋กœ ๊ตฌํ˜„ํ–ˆ์Šต๋‹ˆ๋‹ค.

์œ„ ๊ทธ๋ž˜ํ”„์˜ ์ž…์ถœ๋ ฅ์ด ์•„๋ž˜์™€ ๊ฐ™์„ ๋•Œ ์ถœ๋ ฅํ•ด์•ผ ํ•˜๋Š” ๋ฌธ์ œ๋Š” ์Šคํƒ€ํŠธ ์ง€์ (k=2)์—์„œ ๋ชจ๋“  ๋…ธ๋“œ(n=4)๊นŒ์ง€ ๊ฐ€๋Š” ๋ฐ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„์„ ์ถœ๋ ฅํ•˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
Output: 2

2์—์„œ 1๋ฒˆ๊ณผ 3๋ฒˆ๊นŒ์ง€๋Š” ๋™์‹œ์— ๊ฐˆ์ˆ˜ ์žˆ์œผ๋‹ˆ ๋™์ผํ•˜๊ฒŒ 1์ดˆ๊ฐ€ ๊ฑธ๋ฆฐ๋‹ค๊ณ  ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

for(int i=1; i<=n; i++){
	if(d[i]==1e9) return -1;
	else ans=max(ans,d[i]);
}

์ฝ”๋“œ ๋งˆ์ง€๋ง‰์˜ ์œ„ ๋ถ€๋ถ„์„ ํ†ตํ•ด์„œ ํ•ด๋‹น ๋…ธ๋“œ๋กœ ๊ฐˆ ์ˆ˜ ์—†์„ ๋•Œ๋Š” ๋ฐ”๋กœ -1์„ return ํ•˜์˜€๊ณ , ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์—๋Š” max(ans,d[i])๋ฅผ ํ†ตํ•ด ํ•ด๋‹น ๋…ธ๋“œ๊นŒ์ง€ ๊ฑธ๋ฆฌ๋Š” ์ตœ๊ณ  ์‹œ๊ฐ„์„ ์ •๋‹ต์œผ๋กœ ๊ฐฑ์‹ ํ•ด์ฃผ์—ˆ์Šต๋‹ˆ๋‹ค.(dijkstra๋ฅผ ์‹คํ–‰ํ•˜๋ฉด์„œ ์ถœ๋ฐœ ๋…ธ๋“œ์—์„œ ํ•ด๋‹น ๋…ธ๋“œ๊นŒ์ง€ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„์„ ๊ฐฑ์‹ ํ•ด์คฌ์œผ๋‹ˆ)

๋‹ค๋งŒ ์ฑ„์ ์‹œ๊ฐ„์ด ๊ฝค ์˜ค๋ž˜ ๊ฑธ๋ ค์„œ ๋กœ์ง ๋ฌธ์ œ์ธ ์ค„ ์•Œ์•˜๋Š”๋ฐ ์ œ์ถœํ•  ๋•Œ๋งˆ๋‹ค ์‹œ๊ฐ„์ด ์ฐจ์ด๊ฐ€ ๋‚˜์„œ ๊ทธ๋ƒฅ ์ฑ„์  ์„œ๋ฒ„ ๋ฌธ์ œ์ธ ๊ฑธ๋กœ...

'Algorithm ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป > Leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Leetcode,c++] Add Digits  (0) 2022.03.02
[Leetcode,c++] Happy Number  (0) 2022.03.02
[Leetcode,c++] Majority Element  (0) 2021.11.28
[Leetcode,c++] Valid Anagram  (0) 2021.11.20
[Leetcode,c++] Single Number  (0) 2021.11.19
[Leetcode,c++] Combination Sum II  (0) 2021.11.16

๋Œ“๊ธ€