네카라쿠배 취준반 - 프로그래머스 문제 풀이
[백준 1260] DFS와 BFS (실버 3) 문제 풀이- 자바 Java
개발자로 취직하기
2022. 12. 31. 00:50
0. 자세한 설명은 YouTube 영상으로
- 개발자로 취직하기의 DFS 강의 : https://inf.run/MqJT
[자바/Java] 문과생도 이해하는 DFS 알고리즘! - 입문편 - 인프런 | 강의
자바(Java)로 코딩테스트를 준비하시는 DFS로 분들이 가장 많다는 소식을 들어 제작된 강의입니다 :) 문과 출신의 현업 개발자가 공부한 방식 그대로 설명하고, 지루한 이론 강의는 다 직접 문제를
www.inflearn.com
1. 풀이 코드
import java.util.*;
import java.io.*;
class Main {
final static int MAX = 1000 + 10;
static boolean graph[][];
static boolean visited[];
static ArrayList<Integer> queue;
static int N, M, V;
static void dfs(int idx) {
System.out.print(idx + " ");
visited[idx] = true;
for (int i = 1; i <= N; i++)
if (!visited[i] && graph[idx][i])
dfs(i);
}
static void bfs() {
queue = new ArrayList<>();
visited = new boolean[MAX];
queue.add(V);
visited[V] = true;
while (!queue.isEmpty()) {
int idx = queue.remove(0);
System.out.print(idx + " ");
for (int i = 1; i <= N; i++)
if (!visited[i] && graph[idx][i]) {
visited[i] = true;
queue.add(i);
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
V = Integer.parseInt(st.nextToken());
graph = new boolean[MAX][MAX];
visited = new boolean[MAX];
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine(), " ");
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
graph[x][y] = graph[y][x] = true;
}
dfs(V);
System.out.println();
bfs();
}
}