알고리즘 풀이/백준

[백준][Java] 1260번 DFS와 BFS (DFS, BFS)

배게 2021. 9. 15. 05:22
728x90

BFS 부분 실수

 

for(int i=1; i<=visited.length-1; i++) {

                if(!visited[i] && edge[preNum][i]==1) {

                    q.offer(i);

                    visited[i] = true;

                    System.out.print(i+" ");

                    

                }

            }

 

에서 

 if(!visited[i] && edge[preNum][i]==1) 를

 if(!visited[i] && edge[V][i]==1) 라고함 

 

DFS부분 그대로 갖다 복붙해서 실수 나온 것

 

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
 
 
public class Main {
        
    private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    
    private static void DFS(int V) {
        
        visited[V] = true;
        System.out.print(V+" ");
 
        
        for(int i=1; i<=visited.length-1; i++) {
            if(!visited[i] && edge[V][i]==1) {
                DFS(i);
            }
        }
        
    }
    
    private static void BFS(int V) {
        Queue<Integer> q = new LinkedList<>();
        q.offer(V);
        visited[V] = true;
        System.out.print(V+" ");
        
 
        while(!q.isEmpty()) {
            int preNum = q.poll();
            
            
            for(int i=1; i<=visited.length-1; i++) {
                if(!visited[i] && edge[preNum][i]==1) {
                    q.offer(i);
                    visited[i] = true;
                    System.out.print(i+" ");
                    
                }
            }
            
        }    
    }
    static int[][] edge;
    static boolean[] visited;
    
    public static void main(String[] args) throws IOException{
        String[] str = br.readLine().split(" ");
        int N = Integer.parseInt(str[0]);
        int M = Integer.parseInt(str[1]);
        int V = Integer.parseInt(str[2]);
        
        edge = new int[N+1][N+1];
        visited = new boolean[N+1];
        
        for(int i=0; i<M; i++) {
            str = br.readLine().split(" ");
            edge[Integer.parseInt(str[0])][Integer.parseInt(str[1])] = 1;
            edge[Integer.parseInt(str[1])][Integer.parseInt(str[0])] = 1;
        }
        
        Arrays.fill(visited, false);
        DFS(V);
        System.out.println();
        Arrays.fill(visited, false);
        BFS(V);
        
        
//        bw.write("");
//        bw.flush(); 
//        bw.close();
    }
 
    
 
 
    
}
cs