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
'[알고리즘] > 알고리즘' 카테고리의 다른 글
[알고리즘] 백준 2870번 : 수학숙제 (실버4) (0) | 2022.03.14 |
---|---|
[알고리즘] 백준1159번 : 농구경기 (브론즈2) (0) | 2022.03.05 |
[알고리즘] 송아지 찾기 (BFS) (0) | 2022.02.22 |
[알고리즘] 백준 1759. 암호 만들기 (0) | 2022.02.22 |
[알고리즘] 백준 1182. 부분수열의 합 (0) | 2022.02.17 |