๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜/๋ฌธ์ œ

[์ž๋ฐ”] ๋ฐฑ์ค€ 1260 - DFS์™€ BFS

by applemango2021 2020. 12. 5.

DFS์™€ BFS์— ๋Œ€ํ•œ ๊ธฐ๋ณธ์ ์ธ ๊ฐœ๋…์„ ๋˜์งš์–ด๋ณผ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€ ์‹œ์ž‘ํ•  ๋•Œ๋งˆ๋‹ค ๋‹ค์‹œ ํ’€์–ด๋ณด๊ฒŒ ๋œ๋‹ค.

์ด๋ฒˆ์— ํ‘ผ ์ฝ”๋“œ๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

 import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;

public class Main1260_DFS์™€BFS {

	static int N;
	static int M;
	static int start;
	static Node[] graph;
	static boolean[] visited;
	static StringBuilder sb;
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] str = br.readLine().trim().split(" ");
		
		N = Integer.parseInt(str[0]);
		M = Integer.parseInt(str[1]);
		start = Integer.parseInt(str[2]);
		graph = new Node[N+1];
		visited = new boolean[N+1];
		sb = new StringBuilder();
		
		for(int n=1;n<=N;n++) {
			graph[n] = new Node(n, new ArrayList<Integer>());
		}
		
		int first=0, second=0;
		for(int m=1;m<=M;m++) {
			str = br.readLine().trim().split(" ");
			first = Integer.parseInt(str[0]);
			second = Integer.parseInt(str[1]);
			
			graph[first].link.add(second);
			graph[second].link.add(first);
		}
		
		for(int i=1;i<=N;i++) {
			Collections.sort(graph[i].link);
		}
		
		dfs(start);
		sb.toString().trim();
		sb.append("\n");
		
		visited = new boolean[N+1];
		bfs();
		
		System.out.println(sb.toString());

	}
	
	private static void bfs() {
		visited[start] = true;
		sb.append(start+" ");
		
		Queue<Integer> que = new LinkedList<Integer>();
		que.offer(start);
		
		int tmp;
		ArrayList<Integer> list;
		while(!que.isEmpty()) {
			tmp = que.poll();
			
			list = graph[tmp].link;
			for (Integer i : list) {
				if(!visited[i]) {
					visited[i] = true;
					sb.append(i+" ");
					que.offer(i);
				}
			}
		}
	}

	//์ผ๋‹จ ๋ฐฉ๋ฌธํ•˜๊ธฐ๋งŒ ํ•˜๋ฉด ๋. 
	//๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ฐพ์„ ํ•„์š”๊ฐ€ ์—†์œผ๋ฏ€๋กœ visited[start]์„ ์›๋ณต์‹œ์ผœ๋†“์ง€ ์•Š๋Š”๋‹ค. 
	private static void dfs(int start) {
		visited[start] = true;
		sb.append(start+" ");
		
		ArrayList<Integer> list = graph[start].link;
		for (Integer i : list) {
			if(!visited[i]) {
				dfs(i);
			}
		}
	}

	static class Node{
		int nodeNum;
		ArrayList<Integer> link;
		
		public Node() {
			
		}
		
		public Node(int nodeNum, ArrayList<Integer> link) {
			this.nodeNum = nodeNum;
			this.link = link;
		}
	}
}

๊ตณ์ด Node Class๋ฅผ ๋งŒ๋“ค ํ•„์š”๋Š” ์—†์—ˆ๋Š”๋ฐ ArrayList์˜ ๋ฐฐ์—ด์„ ์–ด๋–ป๊ฒŒ ๋งŒ๋“ค์–ด์•ผ ํ• ์ง€ ๋ชจ๋ฅด๊ฒ ์–ด์„œ Node Class๋ฅผ ๋งŒ๋“ค์—ˆ๋‹ค.

๊ทผ๋ฐ ์ด์ „์— ํ‘ผ ์ฝ”๋“œ๋ฅผ ๋ณด๋‹ˆ๊นŒ ArrayList์˜ ๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด๋†จ๋Š”๋ฐ, ์ง€๊ธˆ๋ด๋„ ์ดํ•ด๊ฐ€ ์ž˜ ์•ˆ ๊ฐ€๋Š”๊ฑฐ ๋ณด๋‹ˆ๊นŒ ๊ทธ๋ƒฅ ์™ธ์›Œ์„œ ๋งŒ๋“ค์—ˆ๋‚˜๋ณด๋‹ค.

 ArrayList<Integer>[] adList = adList = (ArrayList<Integer>[]) new ArrayList[N+1];