알고리즘

<백준> BFS 자바 알고리즘

changha. 2022. 1. 11. 22:56
import java.util.*;

public class Main
{
    static int n, m, k; // n = 정점, m = 간선, k = 시작 노드 
   
	public static void main(String[] args) {
	    Scanner in = new Scanner(System.in);
	    n = in.nextInt();
	    m = in.nextInt();
	    k = in.nextInt();
	    
	    boolean[] visited = new boolean[n + 1];
	    LinkedList<Integer>[] adjList = new LinkedList[n + 1];
	    
	    for(int i = 1; i <= n; i++){
	        adjList[i] = new LinkedList<>();
	    }
	    
	    for(int i = 0; i < m; i++){
	        int v1 = in.nextInt();
	        int v2 = in.nextInt();
	        
	        adjList[v1].add(v2);
	        adjList[v2].add(v1);
	    }
	    for(int i = 1; i <= n; i++){
	        Collections.sort(adjList[i]);
	    }
	    
	    BFS(k, adjList, visited);
	}
	
	private static void BFS(int v, LinkedList<Integer>[] adjList, boolean[] visited){
	    Queue<Integer> queue = new LinkedList<Integer>();
	    visited[v] = true;
	    queue.add(v);
	    
	    while(queue.size() != 0){
	        v = queue.poll();
	        System.out.print(v + " ");
	        
	        Iterator<Integer> iter = adjList[v].listIterator();
	        while(iter.hasNext()){
	            int w = iter.next();
	            if(!visited[w]) {
	                visited[w] = true;
	                queue.add(w);
	            }
	        }
	    }
	    
	}
}