티스토리 뷰

알고리즘/백준

1260번 백준

절취선 2021. 4. 20. 17:38
반응형
package BACKJOON;
import java.io.*;
import java.util.*;
public class back_1260 {
static int[][] arr;
static boolean[] visit;
static int N;
static int M;
static int V;
public static void main(String[] args) throws IOException {
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br1.readLine());
N = Integer.parseInt(st.nextToken()); //node
M = Integer.parseInt(st.nextToken()); // edge
V = Integer.parseInt(st.nextToken()); //start
arr = new int[1001][1001];
visit = new boolean[1001];
for (int i = 0; i < M; i++) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y = sc.nextInt();
arr[x][y] = arr[y][x]=1;
}
dfs(V);
visit = new boolean[1001];
System.out.println();
bfs();
}
public static void dfs(int V) {
visit[V] = true;
System.out.print(V + " ");
for(int i=1; i<=N; i++){
if(arr[V][i] ==1 && visit[i]== false){
dfs(i);
}
}
}
public static void bfs() {
Queue<Integer> queue = new LinkedList<>();
queue.offer(V);
visit[V] = true;
System.out.print(V + " ");
while(!queue.isEmpty()){
int temp = queue.poll();
for(int i=1; i<=N; i++){
if(arr[temp][i]==1 && visit[i]==false){
queue.offer(i);
visit[i]=true;
System.out.print(i + " ");
}
}
}
}
}
view raw back_1260.java hosted with ❤ by GitHub

 

반응형

'알고리즘 > 백준' 카테고리의 다른 글

15649번 백준  (0) 2021.04.20
백준 9251  (0) 2021.04.20
[back_11404]  (0) 2021.03.29
[1197]최소 스패닝 트리(MST) / 스패닝 트리(STP)  (0) 2021.02.14
[백준] 1330번 두 수 비교하기  (0) 2021.02.09
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/04   »
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
글 보관함