[Programmers] Lv3. ๊ฐ€์žฅ ๋จผ ๋…ธ๋“œ | C++

2023. 10. 22. 14:46ใ†Coding Test/Programmers

๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

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

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

programmers.co.kr

 

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

 

์ฒ˜์Œ์—” ๋‹ค์ต์ŠคํŠธ๋ผ(Dijkstra) ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๋จผ์ € ๋– ์˜ฌ๋ ธ๋Š”๋ฐ, BFS๋กœ๋„ ๊ฐ„๋‹จํ•˜๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๊ฒ ๋‹จ ์ƒ๊ฐ์ด ๋“ค์–ด BFS๋กœ ํ’€์—ˆ์Šต๋‹ˆ๋‹ค. ์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

 

  1. ํ–‰ ๋ฒˆํ˜ธ๋Š” ๋…ธ๋“œ์˜ ๋ฒˆํ˜ธ, ์—ด ๋ฒˆํ˜ธ๋Š” ํ–‰ ๋ฒˆํ˜ธ ๋…ธ๋“œ์™€ ์—ฐ๊ฒฐ๋œ ๋‹ค๋ฅธ ๋…ธ๋“œ๋“ค์˜ ๋ฒˆํ˜ธ๋กœ ์ด๋ฃจ์–ด์ง„ 2์ฐจ์› ๋ฐฐ์—ด์„ ์„ ์–ธํ•œ๋‹ค.
  2. 1๋ฒˆ ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ ํ›„ Queue์— ๋„ฃ๊ณ , BFS ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•œ๋‹ค.
  3. Queue์—์„œ ๋…ธ๋“œ(source)๋ฅผ ๊บผ๋‚ธ ํ›„, ํ•ด๋‹น ๋…ธ๋“œ์™€ ์—ฐ๊ฒฐ๋œ ๋‹ค๋ฅธ ๋…ธ๋“œ๋“ค์„ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ ํ›„ Queue์— ๋„ฃ๋Š”๋‹ค.
  4. ์ด ๋•Œ, source ๋…ธ๋“œ์™€ ์—ฐ๊ฒฐ๋œ ๋‹ค๋ฅธ ๋…ธ๋“œ๋“ค์˜ ๊ฑฐ๋ฆฌ๊ฐ’์€ source ๋…ธ๋“œ ๊ฑฐ๋ฆฌ๊ฐ’ + 1๋กœ ๊ฐฑ์‹ ํ•œ๋‹ค.
  5. ๊ฐฑ์‹ ๋œ ๊ฑฐ๋ฆฌ๊ฐ’์„ ๋ณ„๋„์˜ ๋ฐฐ์—ด์— ๋‹ด๋Š”๋‹ค.
  6. ์œ„ ๊ณผ์ •์„ Queue๊ฐ€ ๋นŒ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•œ๋‹ค.
  7. ๊ฑฐ๋ฆฌ๊ฐ’์ด ์ €์žฅ๋œ ๋ฐฐ์—ด์„ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ ํ›„, ์ฒซ ๋ฒˆ์งธ ๊ฐ’์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ์–ด ๋ฆฌํ„ดํ•œ๋‹ค.

 

โœ๏ธ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

struct Node
{
    vector<int> otherNodes;
    int _distance = 0;
};

int BFS(vector<Node>& nodes, const int n, int v)
{
    vector<bool> visited(n + 1, false);
    queue<int> next;
    next.push(v);
    visited[v] = true;

    vector<int> candidates;
    candidates.reserve(n);

    while (!next.empty())
    {
        v = next.front();
        next.pop();

        for (const auto& otherNode : nodes[v].otherNodes)
        {
            if (visited[otherNode])
                continue;

            visited[otherNode] = true;
            int nextDistance = nodes[v]._distance + 1;
            
            nodes[otherNode]._distance = nextDistance;
            candidates.push_back(nextDistance);
            next.push(otherNode);
        }
    }

    sort(candidates.begin(), candidates.end(), greater<int>());
    return std::count(candidates.begin(), candidates.end(), candidates[0]);
}

int solution(int n, vector<vector<int>> edge) {
    // 1. ๋…ธ๋“œ ๋ณ„๋กœ ๊ฐ„์„  ์ •๋ณด ์ •๋ฆฌํ•˜๊ธฐ
    vector<Node> nodes(n + 1);
    for (const auto& e : edge)
    {
        int start = e[0], dest = e[1];
        nodes[start].otherNodes.emplace_back(dest);
        nodes[dest].otherNodes.emplace_back(start);
    }

    // 2. BFS
    int answer = BFS(nodes, n, 1);
    return answer;
}

 

 

728x90
๋ฐ˜์‘ํ˜•