• Home
  • About
    • Ryureka Moment photo

      Ryureka

      Sin Prisa, Sin Pausa

    • About Me
    • Facebook
    • Github
    • Youtube
  • Projects
  • Posts
    • Posts
    • ProblemSolvings
    • Tags
    • Blog
    • Examples
  • ProblemSolving
    • ProblemSolving
    • BOJ
    • Programmers
    • SWEA
    • LeetCode
  • FrontEnd
    • FrontEnd
    • HTML
  • BackEnd
    • BackEnd
    • Server
      • Server
      • Spring
      • NodeJS
    • DataBase
      • DataBase
      • MySQL
      • MongoDB
  • Programming
    • Programming
    • Java
    • JS
    • Python
    • CleanCode
  • ComputerScience
    • DataStructure
    • Algorithm

[BOJ] 1260. DFS와 BFS

16 Apr 2026

Reading time ~1 minute

  • 풀이

풀이

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
	static int N, M, V;	
	static boolean[] check;
	static ArrayList<Integer>[] edge;
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		M = sc.nextInt();
		V = sc.nextInt();
		
		check = new boolean[N+1];
		
		edge = new ArrayList[N+1];
		for(int i = 1; i <= N; i++) {
			edge[i] = new ArrayList<>();
		}
		
		for(int i = 0; i < M; i++) {
			int v1 = sc.nextInt();
			int v2 = sc.nextInt();
			edge[v1].add(v2);
			edge[v2].add(v1);
		}
		
		for(int i = 1; i <= N; i++) {
			Collections.sort(edge[i]);
		}
		
		dfs(V);
		System.out.println();
		check = new boolean[N+1];
		bfs(V);
	}
	
	public static void dfs(int v) {
		check[v] = true;
		System.out.print(v + " ");
		for(int i = 0; i < edge[v].size();i++) {
			int nv = edge[v].get(i);
			if(!check[nv]) {
				dfs(nv);
			}
		}
	}
	
	public static void bfs(int V) {
		Queue<Integer> q = new LinkedList<>();
		q.add(V);
		check[V] = true;
		while(!q.isEmpty()) {
			int v = q.poll();
			System.out.print(v + " ");
			for(int i = 0; i < edge[v].size(); i++) {
				int nv = edge[v].get(i);
				if(!check[nv]) {
					q.add(nv);
					check[nv] = true;
				}
			}
		}
	}
}


DFSBFS Share