1260번: DFS와 BFS
https://www.acmicpc.net/problem/1260
# 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static StringBuilder sb = new StringBuilder();
static boolean[] check;
static int[][] arr;
static int node, line, start;
static Queue<Integer> q = new LinkedList<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
node = Integer.parseInt(st.nextToken());
line = Integer.parseInt(st.nextToken());
start= Integer.parseInt(st.nextToken());
arr = new int[node+1][node+1];
check = new boolean[node+1];
for(int i = 0 ; i < line ; i ++) {
StringTokenizer str = new StringTokenizer(br.readLine());
int a = Integer.parseInt(str.nextToken());
int b = Integer.parseInt(str.nextToken());
arr[a][b] = arr[b][a] = 1;
}
//sb.append("\n");
dfs(start);
sb.append("\n");
check = new boolean[node+1];
bfs(start);
System.out.println(sb);
}
public static void dfs(int start) {
check[start] = true;
sb.append(start + " ");
for(int i = 0 ; i <= node ; i++) {
if(arr[start][i] == 1 && !check[i])
dfs(i);
}
}
public static void bfs(int start) {
q.add(start);
check[start] = true;
while(!q.isEmpty()) {
start = q.poll();
sb.append(start + " ");
for(int i = 1 ; i <= node ; i++) {
if(arr[start][i] == 1 && !check[i]) {
q.add(i);
check[i] = true;
}
}
}
}
}
'코딩테스트 > 자바 문제풀이' 카테고리의 다른 글
[CLASS 3: BFS] 백준 9019 DSLR (0) | 2024.11.27 |
---|---|
[CLASS 3: BFS] 백준 16928 뱀과 사다리 게임 (0) | 2024.11.26 |
[CLASS 3: BFS] 백준 10026 적록색약 (0) | 2024.11.24 |
[CLASS 3: BFS] 백준 7569 토마토 (0) | 2024.11.23 |
[CLASS 3: 자료구조] 백준 5430 AC (0) | 2024.11.22 |