https://www.acmicpc.net/problem/18352
그래프를 입력하고 bfs로 탐색하는 가장 기초적인 문제이다
list = new ArrayList[node+1];
for(int i = 0; i< list.length; i++){
list[i] = new ArrayList<>();
}
for(int i = 0; i< edge; i++){
str = reader.readLine().split(" ");
int a = Integer.parseInt(str[0]);
int b = Integer.parseInt(str[1]);
list[a].add(b);
}
인접리스트로 그래프를 저장해준다
visit = new int[node+1];
Arrays.fill(visit, -1);
방문 리스트를 만들어주고 -1로 채워준다(방문하지 않은 상태)
static void bfs(int node) {
Queue<Integer> Q = new LinkedList<>();
Q.add(node);
visit[node]++;
while(!Q.isEmpty()){
int now = Q.poll();
for(int i : list[now]){
if(visit[i] == -1) {
visit[i] = visit[now]+1;
Q.add(i);
}
}
}
}
탐색 경로를 만들어주고(Queue 생성)
첫 방문지점을 탐색 경로에 더해준다
해당 지점에서 갈 수 있는 지점 하나하나에 대해
만약 이전에 방문하지 않은 지점 일때는 방문 리스트에 현재 거리에 +1을 저장한다
후에 출발할 지점으로 탐색 경로에 저장!
간단해 보이지만 이해하는데에 많은 시간이 걸렸다.
<전체 code>
import java.io.*;
import java.util.*;
public class Q18352 {
static int[] visit;
static List<Integer>[] list;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String[] str = reader.readLine().split(" ");
int node = Integer.parseInt(str[0]);
int edge = Integer.parseInt(str[1]);
int distance = Integer.parseInt(str[2]);
int start = Integer.parseInt(str[3]);
list = new ArrayList[node+1];
for(int i = 0; i< list.length; i++){
list[i] = new ArrayList<>();
}
for(int i = 0; i< edge; i++){
str = reader.readLine().split(" ");
int a = Integer.parseInt(str[0]);
int b = Integer.parseInt(str[1]);
list[a].add(b);
}
visit = new int[node+1];
Arrays.fill(visit, -1);
bfs(start);
int count = 0;
for(int i = 0; i< node+1; i++){
if(visit[i] == distance){
writer.write(i+"\n");
count++;
}
}
if(count == 0){
System.out.println(-1);
}else{
writer.flush();
}
}
static void bfs(int node) {
Queue<Integer> Q = new LinkedList<>();
Q.add(node);
visit[node]++;
while(!Q.isEmpty()){
int now = Q.poll();
for(int i : list[now]){
if(visit[i] == -1) {
visit[i] = visit[now]+1;
Q.add(i);
}
}
}
}
}
'알고리즘 > java' 카테고리의 다른 글
<java> 프로그래머스 베스트 앨범 - Map과 정렬 (0) | 2024.05.20 |
---|---|
<java> 백준 1018 - 완전탐색 (0) | 2024.05.17 |
<java> 백준 14889 - 완전탐색, DFS (0) | 2024.05.17 |
<java> 백준 1092- 그리디 (0) | 2024.03.21 |
<java> 백준 12904 - 그리디 (2) | 2024.03.19 |