๐๏ธ Algorithm/๐ฉ ๋ฐฑ์ค
๐ฉ [๋ฐฑ์ค] [Java] [Silver2] 1260๋ฒ_DFS์ BFS
Dbswnstjd
2024. 1. 8. 00:01
๋ฌธ์
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.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 + " ");
}
}
}
}
}