728x90
https://www.acmicpc.net/problem/1260
1260번: DFS와 BFS
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사
www.acmicpc.net
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
// DFS와 BFS
public class _1260 {
public static boolean[] visit;
public static Queue<Integer> queue = new LinkedList<>();
public static void dfs(boolean[][] graph, int n, int v) {
visit[v] = true;
System.out.print(v + " ");
for (int i = 1; i <= n; i++) {
if (!visit[i] && graph[v][i] == true) {
dfs(graph, n, i);
}
}
}
public static void bfs(boolean[][] graph, int n, int v) {
queue.add(v);
visit[v] = true;
while (!queue.isEmpty()) {
int data = queue.poll();
System.out.print(data + " ");
for (int i = 1; i <= n; i++) {
if (!visit[i] && graph[data][i] == true) {
visit[i] = true;
queue.add(i);
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int v = sc.nextInt();
visit = new boolean[n + 1];
boolean[][] graph = new boolean[n + 1][n + 1];
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
graph[a][b] = true;
graph[b][a] = true;
}
dfs(graph, n, v);
System.out.println();
for (int i = 0; i <= n; i++) {
visit[i] = false;
}
bfs(graph, n, v);
}
}
MEMO
-- DFS와 BFS의 개념이해가 있다면 쉽게 해결 가능한 문제
-- 재귀를 이용한 DFS방식, 자료구조 QUEUE를 이용한 BFS 방식
!! 기본이 가장 중요 !!
728x90
728x90
'백준[baekjoon] > JAVA' 카테고리의 다른 글
백준(baekjoon) [JAVA] - 4963번: 섬의 개수 (0) | 2023.08.23 |
---|---|
백준(baekjoon) [JAVA] - 11724번: 연결 요소의 개수 (0) | 2023.08.20 |
백준(baekjoon) [JAVA] - 15649번: N과 M (1) (0) | 2023.08.17 |
백준(baekjoon) [JAVA] - 1476번: 날짜 계산 (0) | 2023.08.15 |
백준(baekjoon) [JAVA] - 11052번: 카드 구매하기 (0) | 2023.08.13 |