본문 바로가기
개발 관련 공부/알고리즘

백준 11725 트리의 부모 찾기

by 슴새 2021. 8. 26.
반응형

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
	static int parents [];
	static ArrayList <Integer> list [];
	public static void main(String[] args) {
	
		try{
	        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	        int n = Integer.parseInt(br.readLine());
	      //arrayList 한 원소를 배열로... 배열의 한 원소가 어레이리스트인듯 
			 list =new ArrayList [n+1];
			 for(int i=0;i<n+1;i++) {
				 list[i]=new ArrayList<Integer>();
			 }
			 for(int i=0;i<n-1;i++) {
				 String s[]=br.readLine().split(" ");
				 int a=Integer.parseInt(s[0]);
				 int b=Integer.parseInt(s[1]);
				 list[a].add(b);
				 list[b].add(a);
			 }
			 
			 parents=new int[n+1]; // parents[i]=j -> i의 부모는 j
			 bfs();
			 for(int i=2;i<n+1;i++) {			 
					System.out.println(parents[i]);
			  }
			 
	         
	        }catch(Exception e){
	        	
	        	
	        }
		}
		 
		 
		 
	public static void bfs() {
		 Queue<Integer> q=new LinkedList<>();
		 q.offer(1);
		 parents[1]=1;
		  
		 while(!q.isEmpty()) {
			 int temp=q.poll();
			 
			 for(int next:list[temp]){
				//방문x
				 if(parents[next]==0) {
					 q.offer(next);
					 parents[next]=temp;
				 
				 }
			 }
		 
			 
	}
}
}
반응형

'개발 관련 공부 > 알고리즘' 카테고리의 다른 글

유니온 파인드  (1) 2022.09.16
백준 1697 숨바꼭질  (0) 2021.08.25
백준 7569 토마토2  (0) 2021.08.24
백준 7576 토마토  (0) 2021.08.23
백준 1302 베스트셀러  (0) 2021.08.20

댓글