-
백준 1260번: DFS와 BFS코딩 2020. 6. 2. 18:44
문제
그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.
입력
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.
코드
import java.util.*; public class Main { static int n,m; static int[][] cnt; //간선 연결상태 (1:연결, 0:연결x) static boolean[] check; //출력g한 정점(true) static int start; //시작 정점 V public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); start = sc.nextInt(); cnt = new int[1001][1001]; check = new boolean[1001]; //초기값 false for(int i=0; i<m; i++) { //간선 연결 상태 int x = sc.nextInt(); int y = sc.nextInt(); cnt[x][y] = cnt[y][x] = 1; } dfs(start); System.out.println(); check = new boolean[1001]; //초기화 bfs(); } public static void dfs (int i) { check[i] = true; System.out.print(i + " "); for(int j=1; j<=n; j++) { if(cnt[i][j] == 1 && check[j] == false) { dfs(j); } } } public static void bfs () { Queue<Integer> queue = new LinkedList<Integer>(); queue.offer(start); check[start] = true; System.out.print(start + " "); while(!queue.isEmpty()) { int temp = queue.poll(); for(int j=1; j<=n; j++) { if(cnt[temp][j] == 1 && check[j] == false) { queue.offer(j); System.out.print(j + " "); check[j] = true; } } } } }
오류해결
처음에 컴파일 에러가 나왔는데 class 이름을 Main으로 고치니까 해결
그 다음 런타임 에러는 패키지 부분 지우니까 해결됨
'코딩' 카테고리의 다른 글
프로그래머스: 어린 동물 찾기 (0) 2020.06.06 프로그래머스: 동물 수 구하기 (0) 2020.06.05 프로그래머스: 여러 기준으로 정렬하기 (0) 2020.06.05 프로그래머스: 네트워크 (1) 2020.06.04 프로그래머스: 타겟 넘버 (1) 2020.06.03