Hard deck/reindexing d1
026 : DFS와 BFS 출력
서버관리자 페페
2023. 6. 13. 20:48
Cont - 초기화 - D2TP
TP[i] 하나하나가 ArrayList<>이므로 for문으로 sort해줘야 한다
DFS
pairing
- divergence
- phaser
now + connected
진입시 phaser 체크됨
BFS는 DFS와 여러 차이점이 있는데
- 재귀가 아닌 Field필요하여 Queue 생성
- 처음 진입한 것은 sP로 별도 인식
나오는 now와 들어가는 connected를 pairing함
- 진입할때 phaser 체크됨
import java.util.*;
public class Main {
static ArrayList<Integer>[] TP;
static boolean[] visited;
public static void main(String[] args) {
// ISC
Scanner sc = new Scanner(System.in);
int V = sc.nextInt();
int E = sc.nextInt();
int sP = sc.nextInt();
// D2TP
TP = new ArrayList[V+1];
for (int i = 1; i <= V; i++) {
TP[i] = new ArrayList<>();
}
for (int i = 1; i <= E; i++) {
int s = sc.nextInt();
int e = sc.nextInt();
TP[s].add(e);
TP[e].add(s);
}
for (int i = 1; i <= V; i++) {
Collections.sort(TP[i]);
}
// OP
visited = new boolean[V+1];
DFS(sP);
System.out.println();
visited = new boolean[V+1];
BFS(sP);
}
// EM
static void DFS(int now) {
System.out.print(now + " ");
visited[now] = true;
for (int connected : TP[now]) {
if (!visited[connected])
DFS(connected);
}
}
static void BFS(int sP) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(sP);
visited[sP] = true;
while(!queue.isEmpty()) {
int now = queue.poll();
System.out.print(now + " ");
for (int connected : TP[now]) {
if (!visited[connected]) {
visited[connected] = true;
queue.offer(connected);
}
}
}
}
}