๋ฌธ์
https://www.acmicpc.net/problem/1260
ํ์ด
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int[][] arr;
static boolean[] visited;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int N = scan.nextInt(); // ์ ์ ์ ๊ฐ์
int M = scan.nextInt(); // ๊ฐ์ ์ ๊ฐ์
int V = scan.nextInt(); // ํ์์ ์์ํ ์ ์ ๋ฒํธ
//์ธ์ ํ๋ ฌ ์์ฑ
arr = new int[N+1][N+1];
for(int i = 0; i < M; i++) {
int a = scan.nextInt();
int b = scan.nextInt();
arr[a][b] = 1;
arr[b][a] = 1;
}
visited = new boolean[N + 1];
dfs(V);
System.out.println();
visited = new boolean[N + 1];
bfs(V);
}
//๊น์ด์ฐ์ ํ์(์ฌ๊ท)
public static void dfs(int V) {
visited[V] = true;
System.out.print(V + " ");
if(V == arr.length) {
return;
}
for(int j = 1; j < arr.length; j++) {
//์ฐ๊ฒฐ์ ๋์ด์๋๋ฐ, ๋ฐฉ๋ฌธํ์ง ์์๋ค๋ฉด ์ฌ๊ท
if(arr[V][j] == 1 && visited[j] == false) {
dfs(j);
}
}
}
//๋๋น์ฐ์ ํ์(ํ)
public static void bfs(int V) {
Queue<Integer> que = new LinkedList<Integer>();
que.add(V);
visited[V] = true;
System.out.print(V + " ");
while(!que.isEmpty()) {
int temp = que.poll();
for(int i = 1; i < arr.length; i++) {
if(arr[temp][i] == 1 && visited[i] == false) {
que.add(i);
visited[i] = true;
System.out.print(i + " ");
}
}
}
}
}
'๐๏ธ Algorithm > ๐ฉ ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฉ [๋ฐฑ์ค] [Java] [Silver3] 1966๋ฒ_ํ๋ฆฐํฐ ํ (0) | 2024.01.12 |
---|---|
๐ฉ [๋ฐฑ์ค] [Java] [Silver4] 10866_๋ฑ (1) | 2024.01.10 |
๐ฉ [๋ฐฑ์ค] [Java] [Silver5] 2941๋ฒ_ํฌ๋ก์ํฐ์ ์ํ๋ฒณ (0) | 2023.12.10 |
๐ฉ [๋ฐฑ์ค] [Java] [Silver5] 1316๋ฒ_๊ทธ๋ฃน ๋จ์ด ์ฒด์ปค (1) | 2023.12.08 |
๐ฉ [๋ฐฑ์ค] [Java] [Silver5] 4673๋ฒ_์ ํ ๋๋ฒ (0) | 2023.12.07 |