코딩왕랄프👊🏻

[백준] 1260번 DFS와 BFS 본문

백준

[백준] 1260번 DFS와 BFS

hyerm_2 2022. 3. 26. 14:02
반응형
SMALL

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.*;

class Main {
  static int n, m, v;
  static int connect[][];
  static boolean visited[];
  
  public static void dfs(int i) {
    visited[i] = true;
    System.out.print(i + " ");
    
    for(int j = 1; j <= n; j++) {
      if(connect[i][j] == 1 && visited[j] == false) {
        dfs(j);
      }
    }
  }
    
  public static void bfs(){
    Queue<Integer> queue = new LinkedList<Integer>();
    queue.offer(v);
    visited[v] = true;
    System.out.print(v + " ");

    while(!queue.isEmpty()){
      int q = queue.poll();

      for(int i = 1; i <= n; i++){
        if(visited[i]==false && connect[i][q]==1){
          queue.offer(i);
          visited[i] = true;
          System.out.print(i + " ");
        }
      }
    }
  }

    
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    n = sc.nextInt();
    m = sc.nextInt();
    v = sc.nextInt();
    
    connect = new int[n+1][n+1];
    visited = new boolean[n+1];

    for(int i = 1; i <= m; i++){
      int x = sc.nextInt();
      int y = sc.nextInt();
      connect[x][y] = connect[y][x] = 1;
    }
         
    dfs(v);
         
    visited = new boolean[n+1]; 
    System.out.println(); 

    bfs();   
  }
}
반응형
LIST

'백준' 카테고리의 다른 글

[백준] 1065번 한수  (0) 2022.04.12
[백준] 4673번 셀프 넘버  (0) 2022.04.12
[백준] 2231번 분해합  (0) 2022.04.11
[백준] 11724번 연결요소의 개수  (0) 2022.04.03
[백준] 7576번 토마토  (0) 2022.03.29