본문 바로가기
Algorithm

[백준] 1260.DFS와 BFS

by develop growth 2022. 2. 10.

1260.DFS와 BFS

 


개요

 - 이 문제는 DFS와 BFS를 이해할 수 있는 가장 기본이 되는 문제다.

 - DFS는 제귀 함수를 사용하고, BFS는 Queue를 사용하는 개념을 이해할 수 있다. 


문제

그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.

 

입력

 

- 정점의 개수 N(1 ≤ N ≤ 1,000)- 간선의 개수 M(1 ≤ M ≤ 10,000)- 탐색을 시작할 정점의 번호 V - 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다.

 

조건

 - 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다.  - 입력으로 주어지는 간선은 양방향이다.

 

출력

 - 첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.

 

소스

 

package algorithm;

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

public class solveAlgorithm {
	static int N, M, V; // N: 정점의 개수, M: 간선의 개수, V: 시작하는 정점 
	static int[][] map;
	static boolean[] isVisit;
	
	public static void dfs(int start){
	    System.out.print(start + " ");
	    
	    for(int i=1; i<=N; ++i){
	        if(map[start][i] == 1 && isVisit[i] == false){
	            isVisit[i] = true;
	            dfs(i);
	        }
	    }
	}
	
	public static void bfs(int start) {
		Queue<Integer> q = new LinkedList<Integer>();
		
		q.add(start);
		
		while(q.isEmpty() == false) {
			int temp = q.poll();
			
			System.out.print(temp + " ");
			
			for(int i=1; i<=N; i++) {
				if(map[temp][i] == 1 && isVisit[i] == false) {
					isVisit[i] = true;
					q.add(i);
				}
			}
		}
	}
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		map = new int[1001][1001];
		isVisit = new boolean[1001];
		
		N = sc.nextInt();
		M = sc.nextInt();
		V = sc.nextInt();
		
		for(int i=0; i<M; i++) {
			int a,b;
			
			a = sc.nextInt();
			b = sc.nextInt();
			
			
			map[a][b] = 1;
			map[b][a] = 1;
		}
		
		isVisit[V] = true;
		
		dfs(V);
		
		System.out.println();
		
		Arrays.fill(isVisit, false);
		
		isVisit[V] = true;
		bfs(V);	
	}
}

후기

 - 오랜만에 백준 문제를 풀려고 했더니 예전에 풀었던 문제임에도 기억이 잘 나지 않았다. 

 - 백준에서 JAVA언어를 체점할 때 사용하는 파일명은 Main.java 이므로, 제출시 메인 클래스명을 Main으로 하고, 패키지 선언 구문을 없앤 후 제출해야 한다. 


 

'Algorithm' 카테고리의 다른 글

[백준]5052. 전화번호 목록  (0) 2022.03.01
[백준] 14425. 문자열 집합  (0) 2022.02.27
[백준] 2606.바이러스  (0) 2022.02.21
[기본 개념] BFS(Breadth-First Search)  (0) 2022.02.12
[백준] 2178.미로 탐색  (0) 2022.02.11

댓글