슈콩

[BOJ] 백준 1260 DFS와 BFS 본문

Algorithms/Baekjoon

[BOJ] 백준 1260 DFS와 BFS

shukong 2025. 11. 27. 21:19

 

 

[문제]

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