ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 백준 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으로 고치니까 해결

    그 다음 런타임 에러는 패키지 부분 지우니까 해결됨

     

     

    댓글

Designed by Tistory.