반응형
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.io.*; import java.util.*; public class Main { static int[][] node; static boolean[][] visited; static int N; static String result_dfs = ""; static String result_bfs = ""; 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()); // 정점의 개수 int M = Integer.parseInt(st.nextToken()); // 간선의 개수 int V = Integer.parseInt(st.nextToken()); // 탐색을 시작할 정점의 번호 node = new int[N+1][N+1]; visited = new boolean[2][N+1]; for (int i=0; i<M; i++) { st = new StringTokenizer(br.readLine()); int s = Integer.parseInt(st.nextToken()); int e = Integer.parseInt(st.nextToken()); node[s][e] = 1; node[e][s] = 1; } dfs(V); System.out.println(result_dfs); bfs(V); System.out.println(result_bfs); } public static void dfs(int start) { visited[0][start] = true; result_dfs += start + " "; for (int i=1; i<=N; i++) { if (node[start][i] == 1 && !visited[0][i]) { dfs(i); } } } public static void bfs(int start) { Queue<Integer> q = new LinkedList<>(); q.add(start); visited[1][start] = true; while (!q.isEmpty()) { int now = q.poll(); result_bfs += now + " "; for (int i=1; i<=N; i++) { if (node[now][i] == 1 && !visited[1][i]) { visited[1][i] = true; q.add(i); } } } } }
반응형
'알고리즘 > DFS & BFS' 카테고리의 다른 글
[백준]JAVA - 14502번: 연구소 (0) | 2022.10.25 |
---|---|
[백준]JAVA - 16236번: 아기 상어 (0) | 2022.10.20 |
[백준]JAVA - 1520번: 내리막 길 (1) | 2022.10.19 |
[백준]JAVA - 2606번: 바이러스 (0) | 2022.10.11 |
[백준]JAVA - 7576번: 토마토 (0) | 2022.10.07 |