백준 14496번 : 그대, 그머가 되어

M1ndCon·2024년 6월 26일
0

Algorithm

목록 보기
9/32

  • Solved.ac 기준 실버 2
  • 사용언어 C++

문제 해석 및 풀이

설명:

  • 그래프 구성: 주어진 문자쌍을 기반으로 그래프를 구성합니다. 각 문자는 정점으로, 문자쌍은 간선으로 표현됩니다.
  • BFS 알고리즘: 주어진 문자 a에서 시작하여 BFS를 사용해 b로의 최단 경로를 찾습니다.
  • 거리 저장: unordered_map을 사용하여 각 정점까지의 거리를 저장합니다. 처음 시작 정점 a의 거리는 0으로 설정합니다.
  • 경로 탐색: 큐를 사용하여 현재 정점의 모든 인접 정점을 탐색하고, 아직 방문하지 않은 정점을 큐에 추가하면서 거리를 업데이트합니다.
  • 종료 조건: 목표 정점 b에 도달하면 그 때의 거리를 반환합니다. 큐가 비어도 목표 정점 b에 도달하지 못한 경우 -1을 반환합니다.
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
using namespace std;

int bfs(int a, int b, int n, const vector<pair<int, int>>& edges) {
	unordered_map<int, vector<int>> graph;

	for (auto& edge : edges) {
		graph[edge.first].push_back(edge.second);
		graph[edge.second].push_back(edge.first);
	}

	queue<int> que;
	unordered_map<int, int> distance;
	que.push(a);
	distance[a] = 0;

	while (!que.empty()) {
		int current = que.front();
		que.pop();

		if (current == b) {
			return distance[current];
		}

		for (int i : graph[current]) {
			if (distance.find(i) == distance.end()) {
				distance[i] = distance[current] + 1;
				que.push(i);
			}
		}
	}

	return -1;
}

int main() {
	cin.tie(NULL);
	ios_base::sync_with_stdio(false);

	int a, b;
	cin >> a >> b;

	int n, m;
	cin >> n >> m;

	vector<pair<int, int>> edges(m);
	for (int i = 0; i < m; i++) {
		cin >> edges[i].first >> edges[i].second;
	}

	int res = bfs(a, b, n, edges);
	cout << res;
	
	return 0;
}
profile
게임 개발자 지망생

0개의 댓글