Leetcode-1334

Leetcode-1334

 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
32
33
34
35
36
37
38
#include <iostream>
#include <vector>
#include <algorithm>

class Solution {
public:
    int findTheCity(int n, std::vector<std::vector<int>>& edges, int distanceThreshold) {
        int INF = distanceThreshold + 1;
        std::vector<std::vector<int>> dist(n, std::vector<int>(n, INF));
        for (auto& e : edges) {
            dist[e[0]][e[1]] = std::min(dist[e[0]][e[1]], e[2]);
            dist[e[1]][e[0]] = std::min(dist[e[1]][e[0]], e[2]);
        }
        for (int k = 0; k < n; ++k) {
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    if (i != j && dist[i][k] < INF && dist[k][j] < INF) {
                        dist[i][j] = std::min(dist[i][j], dist[i][k] + dist[k][j]);
                    }
                }
            }
        }
        int min_id = 0, min_num = 0x3fff'ffff;
        for (int i = 0; i < n; ++i) {
            int num = 0;
            for (int j = 0; j < n; ++j) {
                if (dist[i][j] < INF) {
                    ++num;
                }
            }
            if (num <= min_num) {
                min_id = i;
                min_num = num;
            }
        }
        return min_id;
    }
};

Leetcode-1334