Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
Tags
- 0으로 채우기
- 프로그래머스 연속된 수의 합 java
- java
- mysql
- 프로그래머스 옹알이 java
- Arrays
- 백준 11723
- java 올림
- Math.floor()
- Codility
- 자바
- Algorithm
- 알고리즘
- 백준 15661
- 백준 16935
- 코딩테스트
- java 내림
- java 반올림
- Math.ceil()
- 백준 17425
- 프로그래머스 네트워크 java
- sort
- 백준 18290
- 네트워크
- 백준 4375
- 프로그래머스 도둑질 java
- time complexity
- 백준 14391
- 프로그래머스 숫자의 표현 java
- 백준 16927
Archives
- Today
- Total
취미처럼
[백준] 1260번 DFS와 BFS 본문
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.*;
import java.io.*;
public class Main {
// 정점 개수
static int N;
// 간선 개수
static int M;
static ArrayList<Integer>[] list;
static boolean[] visit;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
// 탐색 시작
int V = sc.nextInt();
list = new ArrayList[N + 1];
visit = new boolean[N + 1];
for(int i = 0; i < list.length; i++) {
list[i] = new ArrayList<>();
}
// 간선연결상태 저장
for(int i = 0; i < M; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
list[a].add(b);
list[b].add(a);
}
for(int i = 0; i < list.length; i++) {
Collections.sort(list[i]);
}
dfs(V);
sb.append("\n");
visit = new boolean[N + 1];
bfs(V);
System.out.println(sb);
}
public static void dfs(int index) {
visit[index] = true;
// 현재 노드에 해당하는 리스트 모두 하나씩 할당
sb.append(index).append(" ");
for(int i : list[index]) {
if(!visit[i]) {
// 할당한 값을 노드로 바꾸어 재귀호출
dfs(i);
}
}
}
public static void bfs(int index) {
visit[index] = true;
Queue<Integer> queue = new LinkedList<>();
// 1. 탐색 시작 노드를 큐에 넣고 방문처리
queue.add(index);
while(!queue.isEmpty()) {
// 2.큐에서 노드를 꺼냄
int a = queue.poll();
sb.append(a).append(" ");
// 3. 해당 노드의 리스트 중 방문하지 않은 노드를 큐에 넣고 방문처리
for(int i : list[a]) {
if(!visit[i]) {
queue.add(i);
visit[i] = true;
}
}
}
}
}
2021.03.09 - [Algorithm/이론] - 탐색 알고리즘 DFS / BFS
탐색 알고리즘 DFS / BFS
1. DFS(Depth - First Search) 깊이 우선 탐색이라고도 부르며, 그래프에서 깊은 부분을 우선적으로 탐색하는 알고리즘 그래프는 노드와 간선으로 표현되며, 두 노드가 간선으로 연결되어 있다면 두 노
devprogrammer.tistory.com
'Algorithm > 백준' 카테고리의 다른 글
| [백준] 1707번 이분 그래프 (0) | 2021.03.11 |
|---|---|
| [백준] 11724번 연결 요소의 개수 (0) | 2021.03.11 |
| [백준] 13023번 ABCDE (0) | 2021.03.09 |
| [백준] 10866번 덱 (0) | 2021.03.09 |
| [백준] 10845번 큐 (0) | 2021.03.09 |
Comments