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

[Leetcode,c++] Find the City With the Smallest Number of Neighbors at a Threshold Distance

by dkswnkk 2021. 11. 7.

๋ฌธ์ œ

 

Find the City With the Smallest Number of Neighbors at a Threshold Distance - 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 {
    int graph[101][101]={0,};
public:
    int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {


        for (int i = 0; i < 101; i++) {
            fill(graph[i], graph[i] + 101, 1e9);
        }

        for(int i=0; i<n; i++){
            for(int k=0; k<n; k++){
                if(i==k) graph[i][k]=0;
            }
        }

        for(int i=0; i<edges.size(); i++){
            int a = edges[i][0];
            int b = edges[i][1];
            int cost = edges[i][2];
            graph[a][b] = cost;
            graph[b][a] = cost;
        }


        for(int k=0; k<n; k++){
            for(int a=0; a<n; a++){
                for(int b=0; b<n; b++){
                    graph[a][b]=min(graph[a][b],graph[a][k]+graph[k][b]);
                }
            }
        }

        int ans=0,city=1e9;

        for(int i=0; i<n; i++){
            int cnt=0;
            for(int k=0; k<n; k++){
                if(graph[i][k]<=distanceThreshold) cnt++;
            }

            if(city>=cnt){
                ans=i;
                city=cnt;
            }
        }
        return ans;
    }
};

 

ํ’€์ด

ํ•œ ๋„์‹œ์—์„œ distanceThreshold์˜ ๋น„์šฉ์œผ๋กœ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ๋„์‹œ์˜ ๊ฒฝ์šฐ์˜ ์ˆ˜๊ฐ€ ์ œ์ผ ์ ์€ ๋„์‹œ ๋ฒˆํ˜ธ๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค. ๋งŒ์•ฝ ๊ฒฝ์šฐ์˜ ์ˆ˜๊ฐ€ ๊ฐ™์€ ๋„์‹œ ๋ฒˆํ˜ธ๊ฐ€ ์—ฌ๋Ÿฌ ๊ฐœ๋ผ๋ฉด ํฐ ์ˆซ์ž์˜ ๋„์‹œ ๋ฒˆํ˜ธ๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

๊ธฐ๋ณธ์ ์ธ ํ”Œ๋กœ์ด๋“œ-์™€์ƒฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ด์šฉํ•˜์—ฌ ๋ชจ๋“  ๋„์‹œ๊ฒฝ๋กœ์˜ ์ตœ์†Œ๋น„์šฉ์„ ๊ธฐ๋กํ•œ ํ›„, ๋ฌธ์ œ ์กฐ๊ฑด์— ๋งž๋Š” ๋„์‹œ ๋ฒˆํ˜ธ๋ฅผ ์ฐพ์•„ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

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

[Leetcode,c++] Valid Parentheses  (0) 2021.11.09
[Leetcode,c++] Palindrome Number  (0) 2021.11.09
[Leetcode,c++] Search Insert Position  (0) 2021.11.09
[Leetcode,c++] Combination Sum  (0) 2021.11.07
[Leetcode,c++] Multiply-Strings  (0) 2021.11.07
[Leetcode,c++] Longest Common Subsequence  (0) 2021.10.23

๋Œ“๊ธ€