백준 24445번 알고리즘 수업 - 너비 우선 탐색 2

veloger·2022년 12월 29일
0

package test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Q48p269BaekJoon1707 {

	static ArrayList<Integer>[] list;
	static Queue<Integer> qu;
	static int nodes=0;
	static int edges=0;
	static int start=0;
	static int count[]=null;
	
	public static void main(String[] args) throws IOException {
		BufferedReader buf =new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		StringTokenizer st =new StringTokenizer(buf.readLine());
		
		nodes = Integer.parseInt(st.nextToken());
		edges =Integer.parseInt(st.nextToken());
		start =Integer.parseInt(st.nextToken());
		
		list = new ArrayList[nodes+1];
		for(int i=1;i<=nodes;i++) {
			list[i]=new ArrayList<>();
		}
		
		for(int i=0; i<edges;i++) {
			st = new StringTokenizer(buf.readLine());
			int x =Integer.parseInt(st.nextToken());
			int y =Integer.parseInt(st.nextToken());
			list[x].add(y);
			list[y].add(x);
		}
		
		
		for(int i=1;i<=nodes;i++) {
			Collections.sort(list[i], Collections.reverseOrder());
		}
		
		BFS();
		
		for(int i =1 ;i<=nodes;i++) {
			bw.write(count[i]+"\n");
		}
		
		bw.flush();
	}

	private static void BFS() {
		// TODO Auto-generated method stub
		 qu =new LinkedList<>();
		int countNum=1;
		count = new int[nodes+1];
		
		qu.add(start);
		count[start]=countNum;
		++countNum;
		
		while(!qu.isEmpty()) {
			int pop= qu.poll();
			
			for(int i : list[pop]) {
				if(count[i] == 0){
					count[i] += countNum;
					++countNum;
					qu.add(i);
				}
			}
		
		}	
		
	}

}

0개의 댓글