문제
그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.
입력
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.
출력
첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.
[ JAVA ]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Main{ | |
public static void main(String []args){ | |
Scanner scan = new Scanner(System.in); | |
int N = scan.nextInt(); | |
int M = scan.nextInt(); | |
int V = scan.nextInt(); | |
int [][] matrix = new int [N+1][N+1]; // 인덱스로 계산하기 위해 0은 없다고 침 | |
for(int i=0; i<M; i++){ // matrix 설정, 정점 연결된 경우 1 | |
int num1 = scan.nextInt(); | |
int num2 = scan.nextInt(); | |
matrix[num1][num2] = 1; | |
matrix[num2][num1] = 1; | |
} | |
dfs(V, matrix, N); | |
System.out.println(""); | |
bfs(V, matrix, N); | |
} | |
public static void dfs(int V, int[][] matrix, int N){ | |
boolean [] visited = new boolean [N+1]; | |
Stack <Integer> stack = new Stack<>(); | |
stack.push(V); | |
System.out.print(V+" "); | |
visited[V] = true; | |
while(!stack.empty()){ | |
int temp = stack.peek(); | |
boolean flag = false; | |
for(int i=1; i<N+1; i++){ | |
if(matrix[temp][i] == 1 && !visited[i]){ | |
stack.push(i); | |
System.out.print(i+" "); | |
visited[i] = true; | |
flag = true; | |
break; | |
} | |
} | |
if(!flag) | |
stack.pop(); | |
} | |
} | |
public static void bfs(int V, int[][] matrix, int N){ | |
boolean [] visited = new boolean [N+1]; | |
Queue <Integer> queue = new LinkedList<>(); | |
queue.add(V); | |
visited[V] = true; | |
while(queue.size() != 0){ | |
int temp = queue.peek(); | |
queue.remove(); | |
System.out.print(temp+" "); | |
for(int i=1; i<N+1; i++){ | |
if(matrix[temp][i] == 1 && !visited[i]){ | |
queue.add(i); | |
visited[i] = true; | |
} | |
} | |
} | |
} | |
} |

'알고리즘 > DFS와BFS' 카테고리의 다른 글
[ 백준 2606 ] 바이러스 (0) | 2021.06.07 |
---|---|
[ 백준 2178 ] 미로탐색 (0) | 2021.02.10 |
댓글