문제
그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.
입력
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.
출력
첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.
해결 방법
- StringBuilder 으로 dfs와 bfs 로 방문한 점을 넣어서 마지막에 출력
코드
// DFS와 BFS
public class Week08_1260 {
static int[][] map;
static boolean[] visited;
static int start, n, m;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
input();
dfs(start);
sb.append("\n");
bfs();
System.out.println(sb);
}
private static void dfs(int index) {
visited[index] = true;
sb.append(index + " ");
for (int i = 0; i <= n; i++) {
if (!visited[i] && map[index][i] == 1) {
dfs(i);
}
}
}
private static void bfs() {
visited = new boolean[n + 1];
visited[start] = true;
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
while (!queue.isEmpty()) {
int temp = queue.poll();
sb.append(temp + " ");
for (int i = 1; i <= n; i++) {
if (!visited[i] && map[temp][i] == 1) {
visited[i] = true;
queue.add(i);
}
}
}
}
private static void input() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
start = Integer.parseInt(st.nextToken());
map = new int[n + 1][n + 1];
visited = new boolean[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());
map[a][b] = 1;
map[b][a] = 1;
}
}
}
'algorithm' 카테고리의 다른 글
| [BOJ] 2606. 바이러스 (0) | 2022.12.11 |
|---|---|
| [BOJ] 1743. 음식물 피하기 (1) | 2022.12.09 |
| [BOJ] 2740. 행렬 곱셈 (0) | 2022.11.18 |
| [BOJ] 11725. 트리의 부모 찾기 (0) | 2022.11.18 |
| [BOJ] 9934. 완전 이진 트리 (0) | 2022.11.18 |