https://school.programmers.co.kr/learn/courses/30/lessons/132266
๋ฌธ์ ์ค๋ช
๊ฐ์ฒ ๋ถ๋์ ๊ฐ ๋ถ๋์์ด ์ฌ๋ฌ ์ง์ญ์ ๋ฟ๋ฟ์ด ํฉ์ด์ ธ ํน์ ์๋ฌด๋ฅผ ์ํ ์ค์ ๋๋ค. ์ง๋์์ ๊ฐ์ฒ ๋ถ๋๊ฐ ์์นํ ์ง์ญ์ ํฌํจํ ๊ฐ ์ง์ญ์ ์ ์ผํ ๋ฒํธ๋ก ๊ตฌ๋ถ๋๋ฉฐ, ๋ ์ง์ญ ๊ฐ์ ๊ธธ์ ํต๊ณผํ๋ ๋ฐ ๊ฑธ๋ฆฌ๋ ์๊ฐ์ ๋ชจ๋ 1๋ก ๋์ผํฉ๋๋ค. ์๋ฌด๋ฅผ ์ํํ ๊ฐ ๋ถ๋์์ ์ง๋ ์ ๋ณด๋ฅผ ์ด์ฉํ์ฌ ์ต๋จ์๊ฐ์ ๋ถ๋๋ก ๋ณต๊ทํ๊ณ ์ ํฉ๋๋ค. ๋ค๋ง ์ ๊ตฐ์ ๋ฐฉํด๋ก ์ธํด, ์๋ฌด์ ์์ ๋์ ๋ค๋ฅด๊ฒ ๋๋์์ค๋ ๊ฒฝ๋ก๊ฐ ์์ด์ ธ ๋ณต๊ท๊ฐ ๋ถ๊ฐ๋ฅํ ๋ถ๋์๋ ์์ ์ ์์ต๋๋ค.
๊ฐ์ฒ ๋ถ๋๊ฐ ์์นํ ์ง์ญ์ ํฌํจํ ์ด์ง์ญ์ ์ n, ๋ ์ง์ญ์ ์๋ณตํ ์ ์๋ ๊ธธ ์ ๋ณด๋ฅผ ๋ด์ 2์ฐจ์ ์ ์ ๋ฐฐ์ด roads, ๊ฐ ๋ถ๋์์ด ์์นํ ์๋ก ๋ค๋ฅธ ์ง์ญ๋ค์ ๋ํ๋ด๋ ์ ์ ๋ฐฐ์ด sources, ๊ฐ์ฒ ๋ถ๋์ ์ง์ญ destination์ด ์ฃผ์ด์ก์ ๋, ์ฃผ์ด์ง sources์ ์์ ์์๋๋ก ๊ฐ์ฒ ๋ถ๋๋ก ๋ณต๊ทํ ์ ์๋ ์ต๋จ์๊ฐ์ ๋ด์ ๋ฐฐ์ด์ returnํ๋ solution ํจ์๋ฅผ ์์ฑํด์ฃผ์ธ์. ๋ณต๊ท๊ฐ ๋ถ๊ฐ๋ฅํ ๊ฒฝ์ฐ ํด๋น ๋ถ๋์์ ์ต๋จ์๊ฐ์ -1์ ๋๋ค.
๋ด ํ์ด
๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ ์ฌ์ฉํด ๋ชฉ์ ์ง(destination)๋ถํฐ ๋ชจ๋ ์ง์ ๊น์ง์ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ ๋ค ์กฐ๊ฑด์ ๋ง๊ฒ ๋ฐํํด์ฃผ๋ฉด ๋๋ค.
#include <string> #include <vector> #include <queue> using namespace std; vector<int> solution(int n, vector<vector<int>> roads, vector<int> sources, int destination) { vector<int> answer; vector<vector<int>> map(n); int max_int = 999'999; vector<int> distance(n, max_int); priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int,int>>> pq; for(const auto& r : roads) { map[r[0]-1].push_back(r[1]-1); map[r[1]-1].push_back(r[0]-1); } // ๋ชฉ์ ์ง๋ฅผ ํ์ ์ถ๊ฐ pq.push({0, destination-1}); while(!pq.empty()) { auto top = pq.top(); pq.pop(); int r = top.second; int d = top.first; distance[r] = min(distance[r], d); for(int i = 0; i < map[r].size(); ++i) { int nxt = map[r][i]; int dist = d + 1; if(dist < distance[nxt]) { pq.push({dist, nxt}); } } } for(int s : sources) { if(max_int != distance[s-1]) answer.push_back(distance[s-1]); else answer.push_back(-1); } return answer; }
์ฑ์ ๊ฒฐ๊ณผ

'๐ฅ๏ธ Study Note > Coding Test' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Hacker Rank] Organizing Containers of Balls (C++) (1) | 2023.10.09 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค]level.3 - ์นด๋ ์ง ๋ง์ถ๊ธฐ(C++) (1) | 2023.10.05 |
[ํ๋ก๊ทธ๋๋จธ์ค]level.2 - ๊ฐ์ฅ ํฐ ์ ์ฌ๊ฐํ ์ฐพ๊ธฐ(C++) (0) | 2023.09.28 |
[ํ๋ก๊ทธ๋๋จธ์ค]level.3 - ๋ค๋จ๊ณ ์นซ์ ํ๋งค (C++) (0) | 2023.09.26 |
[ํ๋ก๊ทธ๋๋จธ์ค]level.2 - ์ซ์ ๋ณํํ๊ธฐ (C++) (0) | 2023.09.22 |