이전 풀이
https://girokeulhaja.tistory.com/89
[Algorithm] 99클럽 코테 스터디 6일차 TIL | 백준_DFS와 BFS(1260번)
https://www.acmicpc.net/problem/1260dfs와 bfs의 개념만 알고 있다면 풀 수 있는 문제나는 2차원 배열에 입력값을 그대로 담아간선 리스트를 사용하여 그래프를 표현하였다. 문제에 정점이 여러 개인 경우
girokeulhaja.tistory.com
한 달 전에 풀어본 문제를 다시 풀어보았다.
풀고 나니 같은 사람이 푼 문제가 맞나 싶을 정도로 코드가 훨씬 깔끔해졌다는 생각이 든다!
메모리와 시간 모두 이전보다 절약해서 풀기도 하여 뿌듯함에 기록해본다.🫠
ArrayList를 정렬하는 방법이 Collections.sort()임을 기억하자,,,
전체 풀이
import java.util.*;
import java.io.*;
class Main{
static ArrayList<Integer>[] graph;
static boolean[] visited;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int V = Integer.parseInt(st.nextToken());
graph = new ArrayList[N+1];
for(int i = 0; i <= N; i++){
graph[i] = new ArrayList<>();
}
for(int i = 0; i < M; i++){
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
graph[a].add(b);
graph[b].add(a);
}
for(int i = 0; i <= N; i++){
Collections.sort(graph[i]);
}
visited = new boolean[N+1];
dfs(V);
sb.append("\n");
visited = new boolean[N+1];
bfs(V);
System.out.println(sb);
}
public static void dfs(int v){
visited[v] = true;
sb.append(v).append(" ");
for(int n : graph[v]){
if(!visited[n]){
dfs(n);
}
}
}
public static void bfs(int v){
Queue<Integer> queue = new LinkedList<>();
queue.add(v);
visited[v] = true;
while(!queue.isEmpty()){
int q = queue.poll();
sb.append(q).append(" ");
for(int n : graph[q]){
if(!visited[n]){
visited[n] = true;
queue.add(n);
}
}
}
}
}
'Algorithm' 카테고리의 다른 글
[Algorithm] 99클럽 코테 스터디 24일차 TIL | 백준_합분해(2225번) (0) | 2025.02.20 |
---|---|
[Algorithm] 99클럽 코테 스터디 23일차 TIL | 백준_LCS(9251번) (2) | 2025.02.19 |
[Algorithm] 99클럽 코테 스터디 22일차 TIL | 백준_가장 긴 증가하는 부분 수열(11053번) (0) | 2025.02.18 |
[Algorithm] 99클럽 코테 스터디 21일차 TIL | 백준_피보나치 함수(1003번) (1) | 2025.02.17 |
[Algorithm] 99클럽 코테 스터디 20일차 TIL | 백준_최소 회의실 개수(19598번) (5) | 2025.02.14 |