문제 링크입니다: https://school.programmers.co.kr/learn/courses/30/lessons/132266
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
BFS로 간단하게 풀 수 있는 문제였습니다.
알고리즘은 아래와 같습니다.
1. 주어진 roads 벡터를 토대로 양방향 그래프를 만들어 줍니다.
2. sources 벡터를 순회하면서 destination으로부터 source로 갔을 때 최소 경로를 BFS 알고리즘을 통해 구해줍니다.
2.1 이때 도달할 수 없을 경우 answer에 -1을 추가하고 도달할 수 있을 경우 answer에 최단시간을 추가해 줍니다.
3. 2번을 통해 구한 answer를 반환해 줍니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <vector> | |
#include <algorithm> | |
#include <queue> | |
using namespace std; | |
const int MAX = 1e5 + 1; | |
vector<int> graph[MAX]; | |
vector<int> solution(int n, vector<vector<int>> roads, vector<int> sources, int destination) { | |
for (vector<int> road : roads) | |
{ | |
graph[road[0]].push_back(road[1]); | |
graph[road[1]].push_back(road[0]); | |
} | |
vector<int> answer; | |
for (int source : sources) | |
{ | |
if (source == destination) | |
{ | |
answer.push_back(0); | |
continue; | |
} | |
bool canReach = false; | |
bool visited[MAX] = {false,}; | |
queue<pair<int, int>> q; | |
q.push({destination, 0}); | |
visited[destination] = true; | |
while (!q.empty()) | |
{ | |
int cur = q.front().first; | |
int dist = q.front().second; | |
q.pop(); | |
if (cur == source) | |
{ | |
answer.push_back(dist); | |
canReach = true; | |
break; | |
} | |
for (int next : graph[cur]) | |
{ | |
if (visited[next]) | |
{ | |
continue; | |
} | |
visited[next] = true; | |
q.push({next, dist + 1}); | |
} | |
} | |
if (!canReach) | |
{ | |
answer.push_back(-1); | |
} | |
} | |
return answer; | |
} |

개발환경: Programmers IDE
지적, 조언, 질문 환영합니다! 질문 남겨주세요~
반응형
'알고리즘 > programmers' 카테고리의 다른 글
[PCCP 기출문제] 1번 / 붕대 감기 (0) | 2023.11.27 |
---|---|
[Programmers] 카운트 다운 (0) | 2023.11.16 |
[Programmers] 2차원 동전 뒤집기 (0) | 2023.10.20 |
[Programmers] COS Pro 1급 C 모의고사 (0) | 2023.09.05 |
[Programmers] 두 원 사이의 정수 쌍 (1) | 2023.08.30 |