๊ณจ๋“œ5 : bfs ๋ฌธ์ œ์ด๋‹ค.

์ƒ๊ฐ

์ตœ์†Œ ๊ฒฝ๋กœ๋ฅผ ๋ฌป๋Š” ๋ฌธ์ œ๋กœ์จ, ์™„์ „ ํƒ์ƒ‰์œผ๋กœ ํ’€์ดํ•  ์ˆ˜ ์žˆ๋‹ค. ์ด ๋•Œ, ์ค‘์š”ํ•œ ์ ์€, ํ•œ๋ฒˆ์˜ ์Šคํ…์„ ๋„˜์–ด๊ฐ์— ์žˆ์–ด์„œ ์†Œ์ˆ˜์—ฌ์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ, ๊ทธ๋ฆฌ๊ณ  ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค๋Š” ๊ฒƒ์„ ์•Œ๋ ค์ฃผ๊ธฐ ์œ„ํ•œ visited๋ฅผ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด๋‹ค. ์žฌ๋ฐฉ๋ฌธ ํ–ˆ์„ ๊ฒฝ์šฐ, ํƒ์ƒ‰์„ ํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ ๋ถˆ๊ฐ€๋Šฅํ•œ ๊ฒƒ์€ ๋ชจ๋“  ๊ฒฝ๋กœ๋ฅผ ๋‹ค ๊ฒ€ํ† ํ–ˆ์„ ๋•Œ, ๋‹ต์ด ์—†๋Š” ๊ฒฝ์šฐ์ด๋‹ค.

  1. ์†Œ์ˆ˜์ธ๊ฐ€?
  2. ๋ฐฉ๋ฌธํ•œ ์ˆซ์ž์ธ๊ฐ€?
  3. ์ตœ์ข… ๊ฒฝ๋กœ์ธ๊ฐ€?

์ด ์„ธ๊ฐ€์ง€ ์งˆ๋ฌธ์„ ๊ตฌํ˜„ํ•˜๋ฉด ๋‹ต์€ ์‰ฝ๊ฒŒ ๋‚˜์˜จ๋‹ค.

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;
}
 

Reference