[알고리즘]/알고리즘

[알고리즘] 백준 1260. DFS와 BFS

쿠릉쿠릉 쾅쾅 2022. 2. 23. 00:40
728x90

 

 

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

 

1260번: DFS와 BFS

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

www.acmicpc.net

 

 

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

public class Solution {
	
	static int[][] arr;
	
	static int N;
	
	static StringBuilder sb;

	public static void main(String[] args){
		
		Scanner sc = new Scanner(System.in);
		
		N = sc.nextInt();
		
		int M = sc.nextInt();
		
		int V = sc.nextInt();
		
		arr = new int[N][N];
		
		for(int i=0; i<M; i++) {
			int from = sc.nextInt()-1;
			int to = sc.nextInt()-1;
			arr[from][to] = arr[to][from] = 1;
		}
		
		sb = new StringBuilder();
		DFS(arr, new boolean[N], V-1);
		System.out.println(sb.toString());
		BFS(arr, V-1);
		System.out.println(sb.toString());
		
	}
	
	static void BFS(int[][] arr, int start) {
		
		sb = new StringBuilder();
		
		Queue<Integer> queue = new LinkedList<>();
		
		boolean[] check = new boolean[N];
		
		queue.offer(start);
		check[start] = true;
		
		while(!queue.isEmpty()) {
			
			int cur = queue.poll();
			
			sb.append(cur+1).append(" ");
			
			for(int i=0; i<N; i++) {
				if(!check[i] && arr[cur][i]!=0) {
					queue.offer(i);
					check[i] = true;
				}
			}
		}
		
	}
	
	static void DFS(int[][] arr, boolean[] check, int cur) {
		
		sb.append(cur+1).append(" ");
		check[cur] = true;
		
		for(int i=0; i<N; i++) {
			if(!check[i] && arr[cur][i] !=0) {
				DFS(arr, check, i);
			}
		}
		
	}
  
}

 

728x90