-
[java] 백준 1260 : DFS와 BFS알고리즘 2023. 4. 27. 19:05
문제
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.*; public class Main { static int N; static int M; static int K; static int X; static ArrayList<Integer>[] arr; static boolean[] visited; public static void main(String[] args) { Scanner sc = new Scanner(System.in); N = sc.nextInt(); M = sc.nextInt(); K = sc.nextInt(); arr = new ArrayList[N+1]; visited = new boolean[N+1]; for(int i=1; i<=N; i++) { arr[i] = new ArrayList<Integer>(); } for(int i=0; i<M; i++) { int a = sc.nextInt(); int b = sc.nextInt(); arr[a].add(b); arr[b].add(a); } for(int i=1; i<=N; i++) { Collections.sort(arr[i]); } DFS(K); System.out.println(); visited = new boolean[N+1]; BFS(); } static void DFS(int n) { System.out.print(n+" "); visited[n]=true; for(int x : arr[n]) { if(visited[x]==false) { DFS(x);} } } static void BFS() { Queue<Integer> q = new LinkedList<>(); q.add(K); visited[K]=true; while(!q.isEmpty()) { int now = q.poll(); System.out.print(now+" "); for(int x : arr[now]) { if(visited[x]==false) { q.add(x); visited[x]=true; } } } } }
'알고리즘' 카테고리의 다른 글
[java] 백준 2644 : 촌수계산 (0) 2023.05.02 [java] 백준 2606 : 바이러스 (0) 2023.04.30 [java] 백준 14888 : 연산자 끼워넣기 (0) 2023.04.18 [java] 백준 18352 : 특정 거리의 도시찾기 (0) 2023.04.17 [java] LeetCode 234. Palindrome Linked List (0) 2023.04.12