DFS와 BFS
백준 1260번 DFS와 BFS 문제 링크
풀이
- 인접 행렬 arr
- 들렸던 노드 체크 check
- DFS는 재귀로 구현
- BFS에 사용할 큐 q로 구현
제출 코드
import java.io.*;
import java.util.*;
class Main {
public static boolean[] check;
public static int[][] arr;
public static Queue<Integer> q = new LinkedList<>();
public static int N, M, V;
public static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
V = Integer.parseInt(st.nextToken());
arr = new int[N+1][N+1];
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine(), " ");
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
arr[a][b] = 1;
arr[b][a] = 1;
}
check = new boolean[N+1];
dfs(V);
sb.append("\n");
check = new boolean[N+1];
bfs(V);
bw.write(sb.toString());
bw.flush();
}
public static void dfs(int start) {
check[start] = true;
sb.append(start).append(" ");
for (int i = 0; i < N+1; 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).append(" ");
for (int i = 0; i < N+1; i++) {
if (arr[start][i] == 1 && !check[i]) {
q.add(i);
check[i] = true;
}
}
}
}
}