Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 스택
- 우선순위 큐
- 그래프
- BFS
- 유니온 파인드
- 문자열
- 시뮬레이션
- 알고리즘
- 수학
- 백트래킹
- DFS
- 누적 합
- 다이나믹 프로그래밍
- XR Interaction Toolkit
- Unreal Engine 5
- 백준
- 트리
- c++
- 투 포인터
- 다익스트라
- 구현
- 자료구조
- 재귀
- 유니티
- VR
- ue5
- 정렬
- Team Fortress 2
- 브루트포스
- 그리디 알고리즘
Archives
- Today
- Total
1일1알
백준 2479번 경로 찾기 C++ 본문
1. 자신과 다른 모든 코드들을 비교하면서 해밍 거리가 1인 경우만 경로를 추가한다.
2. 입력받은 a에서 b까지 도달할 때까지 bfs탐색을 한다. 탐색 도중에 parent 배열을 이용해서 지나온 경로를 저장한다.
3. parent 배열을 역으로 추적해서 지나온 경로를 추출해서 출력한다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
using namespace std;
using ll = long long;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, k, a, b;
cin >> n >> k;
vector<string> codes(n + 1);
vector<vector<int>> graph(n + 1, vector<int>());
vector<bool> found(n + 1, false);
vector<int> parent(n + 1, -1);
for (int i = 1; i <= n; i++) {
cin >> codes[i];
}
cin >> a >> b;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == j) continue;
int cnt = 0;
for (int y = 0; y < k; y++) {
if (codes[i][y] != codes[j][y]) {
cnt++;
if (cnt > 1) break;
}
}
if (cnt > 1) continue;
graph[i].push_back(j);
}
}
queue<int> q;
q.push(a);
parent[a] = a;
found[a] = true;
while (!q.empty()) {
int curr = q.front();
q.pop();
if (curr == b) {
break;
}
for (auto next : graph[curr]) {
if (found[next]) continue;
found[next] = true;
parent[next] = curr;
q.push(next);
}
}
if (parent[b] == -1) {
cout << -1;
}
else {
vector<int> ans;
int curr = b;
while (true) {
ans.push_back(curr);
curr = parent[curr];
if (curr == parent[curr]) {
ans.push_back(curr);
break;
}
}
for (int i = ans.size() - 1; i >= 0; i--) {
cout << ans[i] << " ";
}
}
};
'알고리즘' 카테고리의 다른 글
백준 10472번 십자뒤집기 C++ (0) | 2022.03.05 |
---|---|
백준 21736번 헌내기는 친구가 필요해 C++ (0) | 2022.03.04 |
백준 12886번 돌 그룹 C++ (0) | 2022.03.02 |
백준 2617번 구슬 찾기 C++ (0) | 2022.03.01 |
백준 2206번 벽 부수고 이동하기 C++ (0) | 2022.02.28 |