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 |
| 31 |
Tags
- 시뮬레이션
- DP
- 코테
- binary search
- dfs
- MySQL
- SQL
- SWEA
- priorityqueue
- 백준
- 투포인터
- 문제해결
- db
- math
- BFS
- 이분탐색
- 문자열
- greedy
- 프로그래머스
- 문제풀이
- Java
- 운동기록
- oracle
- 러닝일지
- 건강
- 자바
- 코딩테스트
- 알고리즘
- BOJ
- COS PRO
Archives
- Today
- Total
슈콩
[BOJ] 백준 1963 소수 경로 본문
[문제]
https://www.acmicpc.net/problem/1963
[소스 코드]
import java.io.*;
import java.util.*;
public class Main {
static int a,b;
static boolean[] prime = new boolean[10000];
public static void main(String[] args) throws IOException {
isPrime();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int t = Integer.parseInt(br.readLine());
while(t-->0) {
st = new StringTokenizer(br.readLine());
a = Integer.parseInt(st.nextToken());
b = Integer.parseInt(st.nextToken());
int[] check = new int[10000];
Arrays.fill(check, -1);
Queue<Integer> q = new LinkedList<>();
q.offer(a);
check[a] = 0;
while(!q.isEmpty()) {
int num = q.poll();
for(int i=0;i<4;i++) {
for(int j=0;j<=9;j++) {
if(i==3 && j==0) continue;
int[] numArr = makeArr(num);
numArr[i] = j;
int numM = makeNum(numArr);
if(check[numM]!=-1 || !prime[numM]) continue;
check[numM] = check[num] + 1;
q.offer(numM);
}
}
}
if(check[b]==-1) System.out.println("impossible");
else System.out.println(check[b]);
}
}
private static void isPrime() {
Arrays.fill(prime,true);
prime[1] = false;
for(int i=2;i*i<10000;i++) {
if(!prime[i]) continue;
for(int j=i*i;j<10000;j+=i) {
prime[j] = false;
}
}
}
private static int[] makeArr(int num) {
int[] arr = new int[4];
for(int i=0;i<4;i++) {
arr[i] = num % 10;
num /= 10;
}
return arr;
}
private static int makeNum(int[] arr) {
int digit = 1;
int num = 0;
for(int i=0;i<4;i++) {
num += arr[i] * digit;
digit *= 10;
}
return num;
}
}'Algorithms > Baekjoon' 카테고리의 다른 글
| [BOJ] 백준 2089 -2진수 (0) | 2025.09.12 |
|---|---|
| [BOJ] 백준 2004 조합 0의 개수 (0) | 2025.09.12 |
| [BOJ] 백준 1929 소수 구하기 (0) | 2025.09.12 |
| [BOJ] 백준 1790 수 이어쓰기 2 (0) | 2025.09.11 |
| [BOJ] 백준 1747 소수&팰린드롬 (0) | 2025.09.11 |