๊ณจ๋5 : bfs ๋ฌธ์ ์ด๋ค.
์๊ฐ
์ต์ ๊ฒฝ๋ก๋ฅผ ๋ฌป๋ ๋ฌธ์ ๋ก์จ, ์์ ํ์์ผ๋ก ํ์ดํ ์ ์๋ค. ์ด ๋, ์ค์ํ ์ ์, ํ๋ฒ์ ์คํ ์ ๋์ด๊ฐ์ ์์ด์ ์์์ฌ์ผ ํ๋ค๋ ๊ฒ, ๊ทธ๋ฆฌ๊ณ ๋ถ๊ฐ๋ฅํ๋ค๋ ๊ฒ์ ์๋ ค์ฃผ๊ธฐ ์ํ visited๋ฅผ ๋ง๋๋ ๊ฒ์ด๋ค. ์ฌ๋ฐฉ๋ฌธ ํ์ ๊ฒฝ์ฐ, ํ์์ ํ์ง ์์ ๊ฒฝ์ฐ ๋ถ๊ฐ๋ฅํ ๊ฒ์ ๋ชจ๋ ๊ฒฝ๋ก๋ฅผ ๋ค ๊ฒํ ํ์ ๋, ๋ต์ด ์๋ ๊ฒฝ์ฐ์ด๋ค.
- ์์์ธ๊ฐ?
- ๋ฐฉ๋ฌธํ ์ซ์์ธ๊ฐ?
- ์ต์ข ๊ฒฝ๋ก์ธ๊ฐ?
์ด ์ธ๊ฐ์ง ์ง๋ฌธ์ ๊ตฌํํ๋ฉด ๋ต์ ์ฝ๊ฒ ๋์จ๋ค.
Code
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <string.h>
using namespace std;
bool isPrime[10000];
bool isVisit[10000];
int T;
void SieveOfEratosThenes(){
memset(isPrime, 1, sizeof(isPrime));
isPrime[0] = false;
isPrime[1] = false;
for (int i = 2; i*i < 10000; i++) {
if (!isPrime[i]) continue;
for (int j = i*i; j < 10000; j += i) {
isPrime[j] = false;
}
}
}
int BFS(int start, int end){
queue<pair<int, int>> q;
q.push(make_pair(start, 0));
while (!q.empty()) {
pair<int, int> now = q.front();
q.pop();
isVisit[now.first] = true;
if (now.first == end) return now.second;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 10; j++) {
if (i == 0 && j == 0) continue;
string now_s = to_string(now.first);
int nowDepth = now.second;
now_s[i] = char('0' + j);
int candidate = stoi(now_s);
if (!isVisit[candidate] && isPrime[candidate]) {
q.push(make_pair(candidate, nowDepth+1));
}
}
}
}
return -1;
}
int main(){
// cout << char('0' + 7);
cin >> T;
SieveOfEratosThenes();
for (int tc = 0; tc < T; tc++) {
memset(isVisit, 0, sizeof(isVisit));
int a, b;
cin >> a >> b;
int result = BFS(a, b);
if (result == -1) cout << "Impossible" << '\n';
else cout << result << '\n';
}
return 0;
}