BOJ_S2_2644
π [S2_2644] μ΄μκ³μ°
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static StringTokenizer st;
static int[][] arr;
static boolean[][] v;
static int cnt, res;
static int n;
static int res_start, res_end;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
// μ 체 μ¬λμ μ
n = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine(), " ");
// κ³μ°ν΄μΌνλ μ΄μ
res_start = Integer.parseInt(st.nextToken());
res_end = Integer.parseInt(st.nextToken());
// κ΄κ³μ κ°μ
int m = Integer.parseInt(br.readLine());
arr = new int[n+1][n+1];
v = new boolean[n+1][n+1];
res = 0;
for(int i=0; i<m; i++){
st = new StringTokenizer(br.readLine(), " ");
int start = Integer.parseInt(st.nextToken());
int end = Integer.parseInt(st.nextToken());
arr[start][end] = arr[end][start] = 1;
}
dfs(res_start);
if(res == 0){
sb.append(-1);
}
else {
sb.append(res);
}
System.out.println(sb);
}
static void dfs(int start){
// κΈ°μ 쑰건
if(start == res_end){
res = cnt;
return;
}
for(int i=1; i<n+1; i++){
if(arr[start][i] == 1 && !v[start][i]){
// λ°©λ¬Έ μ²λ¦¬
v[start][i] = v[i][start] = true;
cnt++;
dfs(i);
cnt--;
}
}
}
}
π€ λμ μκ°
μ΄ λ¬Έμ λ μ²μ λ³΄κ³ μ§ν©μΌλ‘ νμ΄μΌ νλ λΌκ³ μκ°μ νλλ° νΈλ¦¬λ₯Ό κ·Έλ €λ³΄λ μλ 1μ΄ μ΄κ³ μμ 2μ΄μΈλ° μλ κ²°κ΅ νΌμ³λ³΄λ©΄ μλ‘ ν μΉΈ κ°λ€κ° λ€μ λ°μΌλ‘ κ°λ κ±°μ¬μ κ·Έλ₯ κ²½λ‘μ κΈΈμ΄λ₯Ό ꡬν΄μ£Όλ©΄ λλ κ²μ΄μλ€.
κ·Έλμ dfs μκ³ λ¦¬μ¦μ μ΄μ©ν΄μ κΉμ΄ μ°μ νμμ ν΄μ£Όμλ€.
κ·Έλ¦¬κ³ λ°©ν₯μ±μ΄ μκΈ° λλ¬Έμ μ
λ ₯μ λ°μ λ μ λ°©ν₯ λ€ ν΄μ£Όμλ€.
λ¬Έμ μμ κ²½λ‘μ κΈΈμ΄λ₯Ό ꡬν΄μΌνλ κ²μ μλ€λ©΄ μ΄λ ΅μ§ μκ² κ΅¬νν μ μμμ κ±°λ€.