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.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int N, M, V;
static boolean[] visited;
static int[][] arr;
static Queue<Integer> queue = new LinkedList();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
V = sc.nextInt();
arr = new int[N + 1][N + 1];
visited = new boolean[arr.length];
for (int i = 0; i < M; i++) {// 0 1 2 3 4 5
int x = sc.nextInt(); // 1
int y = sc.nextInt();// 2
arr[x][y] = 1;
arr[y][x] = 1;
}
// for (int i = 0; i < N; i++) {
// System.out.println(Arrays.toString(arr[i]));
// }
int v = V;
DFS(v);
System.out.println();
visited = new boolean[arr.length];
BFS(v);
}// eom
public static void DFS(int v) {
System.out.print(v+" ");
visited[v] = true;//방문 true
for (int i = 0; i < arr[v].length; i++) {
if(arr[v][i]==1 && !visited[i]) {
DFS(i);
}
}
}
public static void BFS(int v) {
queue.add(v);
visited[v] = true;
while(!queue.isEmpty()) {
int nv = queue.poll();
System.out.print(nv+" ");
for (int i = 0; i < arr[nv].length; i++) {
if(arr[nv][i]==1 && !visited[i]) {
queue.offer(i);
visited[i] = true;
}
}
}
}
}
'ALGORITHM > 프로그래머스 | 백준 | 삼성 | 카카오' 카테고리의 다른 글
[백준] 2178번 미로탐색 (0) | 2020.04.01 |
---|---|
[백준] 2630번 색종이 만들기 (0) | 2020.04.01 |
[백준] 2468번 안전영역 (0) | 2020.04.01 |
[백준] 1012번 유기농 배추 (0) | 2020.04.01 |
[백준] 7576 토마토 (0) | 2020.03.31 |