π» Coding Problems Solving/DFS | BFS | Backtracking
[BOJ 1260] DFSμ BFS
Kim_dev
2022. 7. 1. 17:36
[BOJ 1260] DFSμ BFS
1. λ¬Έμ : Link
dfs μ bfs 묻λ λ¬Έμ
2. νμ΄
μ΄μ μ¬ κ°μ΄ μ‘νλ€ (2023.04.07)
link[i][j] = link [j][i] = 1 (μ°κ²°λ μ μ΄ μλ€κ³ νμνλκ² μ€μ)
* Eλ₯Ό μννλ κ²μ΄ μλ !
* μ°κ²°λ κ°μ μ€ λ€μ μ«μκ° μμ κ² λΆν° νμν΄μΌνκΈ° λλ¬Έ
3. μ½λ
package baekjoon;
import java.io.IOException;
import java.util.*;
public class Main {
//ν¨μμμ μ¬μ©ν λ³μλ€
static int[][] link; //κ°μ μ°κ²°μν
static boolean[] visited; //νμΈ μ¬λΆ
static int V; //μ μ κ°μ
static int E; //κ°μ κ°μ
static int start; //μμμ μ
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
V = sc.nextInt();
E = sc.nextInt();
start = sc.nextInt();
link = new int[1001][1001]; //μ’νλ₯Ό κ·Έλλ‘ λ°μλ€μ΄κΈ° μν΄ +1ν΄μ μ μΈ
visited = new boolean[1001]; //μ΄κΈ°κ° False
//κ°μ μ°κ²°μν μ μ₯
for(int i = 0; i < E; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
link[x][y] = link[y][x] = 1;
}
dfs(start); //dfsνΈμΆ
visited = new boolean[1001]; //νμΈμν μ΄κΈ°ν
System.out.println(); //μ€λ°κΏ
bfs(); //bfsνΈμΆ
}
//μμμ μ λ³μλ‘ λ°μ νμΈ, μΆλ ₯ ν λ€μ μ°κ²°μ μ μ°Ύμ μμμ μ λ³κ²½νμ¬ μ¬νΈμΆ
public static void dfs(int cur) {
visited[cur] = true;
System.out.print(cur + " ");
for(int j = 1; j <= V; j++) {
if(link[cur][j] == 1 && !visited[j]) {
dfs(j);
}
}
}
public static void bfs() {
Queue<Integer> queue = new LinkedList<Integer>();
queue.offer(start);
visited[start] = true;
System.out.print(start + " ");
while(!queue.isEmpty()) {
int cur = queue.poll();
for(int j = 1; j <= V; j++) {
if(link[cur][j] == 1 && !visited[j]) {
queue.offer(j);
visited[j] = true;
System.out.print(j + " ");
}
}
}
}
}