https://www.acmicpc.net/problem/2644
2644번: 촌수계산
사람들은 1, 2, 3, …, n (1 ≤ n ≤ 100)의 연속된 번호로 각각 표시된다. 입력 파일의 첫째 줄에는 전체 사람의 수 n이 주어지고, 둘째 줄에는 촌수를 계산해야 하는 서로 다른 두 사람의 번호가 주어
www.acmicpc.net

1. 나의풀이
<bash />
import java.util.*;
import java.io.*;
public class Main {
static List<Integer>[] family;
static boolean[] visited;
static int answer=-1;
public static void dfs(int a, int b, int cost){
if(a==b){
answer=cost;
}
visited[a]=true;
for(int i=0; i<family[a].size(); i++){
int temp=family[a].get(i);
if(visited[temp] == false){
dfs(temp, b, cost+1);
}
}
}
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken()); //전체 사람의 수
family= new ArrayList[n+1];
visited= new boolean[n+1];
for(int i=0; i<=n; i++){
family[i]= new ArrayList<>();
}
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());//사람 a
int b = Integer.parseInt(st.nextToken());//사람 b
st = new StringTokenizer(br.readLine());
int m= Integer.parseInt(st.nextToken());//관계의 개수
for(int i=0; i<m; i++){
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
family[x].add(y);
family[y].add(x);
}
dfs(a,b,0);
bw.write(Integer.toString(answer));
bw.flush();
br.close();
bw.close();
}
}
'코테풀이' 카테고리의 다른 글
[프로그래머스] 바탕화면 정리 java 풀이(level1) (0) | 2023.04.20 |
---|---|
[프로그래머스] 공원 산책 java 풀이 (level1) (0) | 2023.04.20 |
[백준] BOJ - 4963 섬의 개수 java (실버2) (0) | 2023.04.12 |
[백준] BOJ - 11724 연결 요소의 개수 java(실버2) (0) | 2023.04.12 |
[백준] BOJ - 2075 N번째 큰 수 java (실버2) (0) | 2023.04.06 |