문제:
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 {
public static ArrayList<ArrayList<Integer>> arr = new ArrayList<>();
public static int n;
public static int m;
public static int start;
public static boolean [] visDfs = new boolean[1005];
public static void bfs(){
boolean [] vis = new boolean[1005];
Queue<Integer> q = new LinkedList<>();
q.add(start);
vis[start] = true;
while(!q.isEmpty()){
int cur = q.poll();
System.out.print(cur+" ");
for(int k : arr.get(cur)){
if(vis[k]) continue;
q.add(k);
vis[k] = true;
}
}
}
public static void dfs(int cur){
visDfs[cur] = true;
System.out.print(cur+" ");
for(int nxt : arr.get(cur)){
if(visDfs[nxt]) continue;
dfs(nxt);
}
}
public static void main(String[] args) throws IOException{
Scanner sc = new Scanner(System.in);
n = sc.nextInt(); // node
m = sc.nextInt(); // edge
start = sc.nextInt(); // start num
for(int i=0;i<=n;i++){
arr.add(new ArrayList<>());
}
for(int i=0;i<m;i++){
int u = sc.nextInt(); // node
int v = sc.nextInt(); // edge
arr.get(u).add(v);
arr.get(v).add(u);
}
for(int i=1;i<=n;i++){
Collections.sort(arr.get(i));
}
// arr complete
dfs(start);
System.out.println();
bfs();
}
}
'Java > 백준' 카테고리의 다른 글
[Java][1766] 문제집 (0) | 2023.02.16 |
---|---|
[Java][2623] 음악프로그램 (0) | 2023.02.15 |
[Java][16165] 걸그룹 마스터 준석이 (0) | 2023.01.27 |
[Java][13414] 수강신청 (0) | 2023.01.27 |
[Java][22862] 가장 긴 짝수 연속한 부분 수열 (large) (1) | 2023.01.14 |