슈콩

[BOJ] 1260 DFS와 BFS 본문

Algorithms/Baekjoon

[BOJ] 1260 DFS와 BFS

shukong 2026. 1. 8. 23:05

[문제]

 

https://www.acmicpc.net/problem/1260

 

 

 

[소스 코드]

import java.util.*;
import java.io.*;

public class Solution {
	static int n;
	static boolean[][] visit;
	static boolean[] check;
	public static void main(String[] args) throws IOException {
		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());
		visit = 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());
			visit[a][b] = visit[b][a] = true;
		}
		check = new boolean[n+1];
		check[v] = true;
		System.out.print(v+" ");
		dfs(v,0);
		System.out.println();
		System.out.print(v+" ");
		bfs(v);
	}
	private static void dfs(int idx,int cnt) {
		if(cnt==n) {
			return;
		}
		for(int i=1;i<=n;i++) {
			if(visit[idx][i] && !check[i]) {
				System.out.print(i+" ");
				check[i] = true;
				dfs(i,cnt+1);
			}
		}
	}
	private static void bfs(int start) {
		Queue<Integer> q = new LinkedList<>();
		check = new boolean[n+1];
		q.offer(start);
		check[start] = true;
		while(!q.isEmpty()) {
			int v = q.poll();
			for(int i=1;i<=n;i++) {
				if(visit[v][i] && !check[i]) {
					check[i] = true;
					q.offer(i);
					System.out.print(i+" ");
				}
			}
		}
	}
}

'Algorithms > Baekjoon' 카테고리의 다른 글

[BOJ] 2606 바이러스  (0) 2026.01.20
[BOJ] 2178 미로 탐색  (0) 2026.01.09
[BOJ] 19236 청소년 상어  (0) 2025.12.17
[BOJ] 17825 주사위 윷놀이  (5) 2025.12.16
[BOJ] 17822 원판돌리기  (0) 2025.12.12