Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | |||||
| 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| 10 | 11 | 12 | 13 | 14 | 15 | 16 |
| 17 | 18 | 19 | 20 | 21 | 22 | 23 |
| 24 | 25 | 26 | 27 | 28 | 29 | 30 |
| 31 |
Tags
- BOJ
- 러닝일지
- 문제풀이
- 백준
- 이분탐색
- 운동기록
- math
- greedy
- COS PRO
- 알고리즘
- 코테
- MySQL
- priorityqueue
- dfs
- 투포인터
- db
- 프로그래머스
- SWEA
- oracle
- DP
- 코딩테스트
- 문제해결
- 시뮬레이션
- Java
- SQL
- 자바
- binary search
- 건강
- BFS
- 문자열
Archives
- Today
- Total
슈콩
[BOJ] 백준 1260 DFS와 BFS 본문

[문제]
https://www.acmicpc.net/problem/1260
[소스 코드]
import java.io.*;
import java.util.*;
public class Main {
static int n;
static boolean[] visit;
static boolean[][] edge;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
edge = new boolean[n+1][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());
edge[a][b] = edge[b][a] = true;
}
visit = new boolean[n+1];
System.out.print(v+" ");
dfs(v);
System.out.println();
bfs(v);
}
private static void dfs(int v) {
visit[v] = true;
for(int i=1;i<=n;i++) {
if(edge[v][i] && !visit[i]) {
System.out.print(i+" ");
dfs(i);
}
}
}
private static void bfs(int v) {
Queue<Integer> q = new LinkedList<>();
visit = new boolean[n+1];
q.offer(v);
visit[v] = true;
System.out.print(v+" ");
while(!q.isEmpty()) {
int curr = q.poll();
for(int i=1;i<=n;i++) {
if(edge[curr][i] && !visit[i]) {
System.out.print(i+" ");
visit[i] = true;
q.offer(i);
}
}
}
}
}'Algorithms > Baekjoon' 카테고리의 다른 글
| [BOJ] 2606 바이러스 (0) | 2025.11.27 |
|---|---|
| [BOJ] 2178 미로탐색 (0) | 2025.11.27 |
| [BOJ] 백준 1799 비숍 (0) | 2025.11.26 |
| [BOJ] 백준 11600 구간 합 구하기 5 (0) | 2025.11.12 |
| [BOJ] 백준 11659 구간 합 구하기 4 (0) | 2025.11.12 |