https://www.acmicpc.net/problem/1260
그래프 이론, 그래프 탐색, 너비 우선 탐색, 깊이 우선 탐색
그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.
첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.
DFS는 재귀를 가지고 풀이,
BFS는 Queue(LinkedList를 이용하여 구현)를 이용하여 풀이
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.LinkedList;
public class Main {
static ArrayList<ArrayList<Integer>> graph;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int nodeCount = Integer.parseInt(st.nextToken());
int lineCount = Integer.parseInt(st.nextToken());
int fisrtNode = Integer.parseInt(st.nextToken());
boolean[] visited_dfs = new boolean[nodeCount+1];
boolean[] visited_bfs = new boolean[nodeCount+1];
graph = new ArrayList<>();
for (int i = 0; i < nodeCount+1; i++) {
graph.add(new ArrayList<Integer>());
}
for (int i = 0; i < lineCount; i++) {
StringTokenizer st1 = new StringTokenizer(br.readLine());
int node1 = Integer.parseInt(st1.nextToken());
int node2 = Integer.parseInt(st1.nextToken());
graph.get(node1).add(node2);
graph.get(node2).add(node1);
}
for (ArrayList<Integer> list : graph) {
Collections.sort(list);
}
dfs(fisrtNode, visited_dfs);
System.out.println();
bfs(fisrtNode, visited_bfs);
}
static void dfs(int firstNode, boolean[] visited){
int nodeIndex = firstNode;
visited[nodeIndex] = true;
System.out.print(nodeIndex+" ");
for (int node : graph.get(firstNode)) {
if(!visited[node]){
dfs(node,visited);
}
}
}
static void bfs(int firstNode, boolean[] visited){
Queue<Integer> queue = new LinkedList<>();
int nodeIndex = firstNode;
queue.add(nodeIndex);
while(!queue.isEmpty()){
int node = queue.poll();
if(!visited[node]){
System.out.print(node+" ");
for (int linkedNode : graph.get(node)) {
queue.add(linkedNode);
}
visited[node] = true;
}
}
}
}
'CS > 알고리즘' 카테고리의 다른 글
DP(동적 프로그래밍) (0) | 2024.02.21 |
---|---|
BFS(너비우선탐색) - 최단 경로 문제를 푸는 알고리즘 (0) | 2024.02.18 |
두 수의 최대공약수는 유클리드 호제법 (0) | 2024.02.08 |
도수 정렬 (0) | 2024.01.04 |
힙 정렬 (0) | 2024.01.04 |