DFS와 BFS 수행결과를 출력하면 된다.
순서보장 및 중복제거를 위해 HashSet을 사용했다.
해시셋을 그냥 출력해버리는 바람에 한 번 틀리고, 클래스명 Main으로 안고쳐서 한 번 틀리고, 패키지명 안 지워서 한 번 틀린 것 빼면 바로 맞혔다고 볼 수 있다! ^_ㅠ
package baekjoon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main_1260 {
static boolean[][] dfs;
static boolean[][] bfs;
static boolean[] visit;
static int N;
static int M;
static HashSet<Integer> hs = new LinkedHashSet<>();
static HashSet<Integer> hs2 = new LinkedHashSet<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
N = Integer.valueOf(st.nextToken()); // 정점의 개수
M = Integer.valueOf(st.nextToken()); // 간선의 개수
int V = Integer.valueOf(st.nextToken()); // 탐색 시작 정점 번호
dfs = new boolean[N+1][N+1];
bfs = new boolean[N+1][N+1];
visit = new boolean[N+1];
// 간선이 연결하는 두 정점의 번호
for(int i=0; i<M; i++) {
StringTokenizer st2 = new StringTokenizer(br.readLine(), " ");
int a = Integer.valueOf(st2.nextToken());
int b = Integer.valueOf(st2.nextToken());
dfs[a][b] = true;
bfs[a][b] = true;
dfs[b][a] = true;
bfs[b][a] = true;
}
dfs(V);
bfs(V);
//System.out.println(hs);
for (Integer a : hs.toArray(new Integer[hs.size()])) {
System.out.print(a+" ");
}
System.out.println();
//System.out.println(hs2);
for (Integer a : hs2.toArray(new Integer[hs2.size()])) {
System.out.print(a+" ");
}
}
public static void dfs(int i) {
if (!visit[i]) {
hs.add(i);
visit[i] = true;
for (int j = 1; j <= N; j++) {
if(dfs[i][j]) {
dfs(j);
}
}
}
}
public static void bfs(int i) {
Queue<Integer> q = new LinkedList<>();
Queue<Integer> q2 = new LinkedList<>();
q.add(i);
while (!q.isEmpty()) {
int start = q.poll();
q2.add(start);
//System.out.println(start);
hs2.add(start);
for (int j = 1; j <= N; j++) {
// 이미 다 돈 정점은 q2에 빼줘서 중복 체크
if(bfs[start][j] && !q2.contains(j)) {
//System.out.println(start+ " "+ j);
q.add(j);
}
}
}
}
}
👩💻 풀이
일단 간선이 연결된 정점들을 모두 배열에 담아 true로 값을 넣어줬다. 반대로도 넣어줘야 dfs에서 순서대로 접근이 가능하다!
연결된 모든 depth를 다 방문해야하므로 for문을 돌려 해당 정점의 모든 연결된 정점들을 체크하여 방문한다.
bfs는 큐에 방문할 정점을 담고 가장 가까운 정점부터 방문해야 하므로 다 돌때까지 큐에만 담아준다. 반복문이 끝나면 큐에 들어간 정점을 차례로 방문하게 된다. 이때 이미 방문이 완료한 정점은 또 다른 큐에 넣어 중복을 제거한다.
설명을 잘 못해서 나만 이해하는 풀이가 돼버렸다..