-
BFS
1. BFS(Breadth-First Search : 너비 우선 탐색)
시작 정점으로부터 가까운 정점들을 먼저 방문하고 멀리 떨어져 있는 정점을 나중에 방문하는 순회 방법.
방문한 정점과 인접한 정점들 중 방문하지 않은 정점을 큐(FIFO)에 삽입.
https://commons.wikimedia.org/wiki/File:Animated_BFS.gif
File:Animated BFS.gif - Wikimedia Commons
No higher resolution available.
commons.wikimedia.org
노드를 넓게 탐색한다.
BFS는 시작 정점으로부터 다른 정점까지의 간선의 수를 최소로 하는 경로를 구한다.# BFS 활용 사례
- 라우팅(routing) : 통신망에서 홉 카운트를 최소로 하는 경로
- 네트워크 브로드캐스트
2. BFS 장단점
# BFS 장점
- 답이 되는 경로가 여러 개인 경우에도 최단경로 보장
# BFS 단점
- 해가 존재하지 않는다면 유한 그래프(finite graph)의 경우에는 모든 그래프를 탐색한 후에 실패로 끝난다.
3. 인접 리스트를 이용한 BFS 구현 (Java)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152public class Node {int vertex;Node next;}public class AdjList {public Node head; //리스트의 헤드//인접리스트의 헤드로 새 정점 삽입public void insert(int v) {Node new_node = new Node();new_node.vertex = v;new_node.next = head;head = new_node;}}public class Queue {public Node first; //큐의 맨 앞 노드public Node last; //큐의 마지막 노드public int size; //큐 사이즈//큐에 정점 v를 last로 삽입public void enqueue(int v) {Node new_node = new Node();new_node.vertex = v;new_node.next = null;if(size == 0)first = last = new_node;else {last.next = new_node;last = new_node;}size++;}//큐에서 (first) 삭제 (FIFO)public int dequeue() {int v = first.vertex;first = first.next;size--;if(size == 0) last = null;return v;}}public class Graph {public int V; //정점의 개수public int E; //간선의 개수public AdjList[] adj; //정점별 인접리스트의 배열//주어진 정점 개수로 그래프 생성하기public Graph(int V) {this.V = V;this.E = 0;adj = new AdjList[V];for(int v=0;v<V;v++)adj[v] = new AdjList();}//비방향 그래프 : 정점 v와 정점 w를 잇는 양방향 간선 추가public void addEdge(int v, int w) {adj[v].insert(w); //v->wadj[w].insert(v); //w->vE++;}}public class BFS {public boolean[] visited; //정점의 방문여부public int[] edgeTo; //DFS에 포함되는 간선(edgeTo[i]->i)//시작정점을 s로 하는 너비우선탐색public BFS(Graph G, int s) {visited = new boolean[G.V];edgeTo = new int[G.V];Queue q = new Queue();visited[s] = true;q.enqueue(s);while(q.size > 0) {int v = q.dequeue();System.out.print(v+ " "); //방문순서:코드 확인용Node node = G.adj[v].head;while(node != null) {int w = node.vertex;if(!visited[w]) { //정점 w를 아직 방문하지 않았으면edgeTo[w] = v;visited[w] = true;q.enqueue(w);}node = node.next;}}}}import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;public class GraphTraversalTest {public static void main(String[] args) {String fname = "Graph_2.txt";BufferedReader in = null;try {in = new BufferedReader(new FileReader(fname));int n = Integer.parseInt(in.readLine());int m = Integer.parseInt(in.readLine());Graph g = new Graph(n);for(int i=0;i<m;i++) {String[] vs = new String[2]; String line = in.readLine();vs = line.split(" ");g.addEdge(Integer.parseInt(vs[0]), Integer.parseInt(vs[1]));}in.close();System.out.println("<Graph>");for(int v=0;v<g.V;v++) {System.out.print(v + " : ");Node node = g.adj[v].head;while(node != null) {System.out.print(node.vertex + " ");node = node.next;}System.out.println();}System.out.println("<BFS>");BFS bfs = new BFS(g, 0);System.out.println("");for(int v=0; v< g.V; v++) {System.out.println(v + " | " + bfs.edgeTo[v]);}} catch(IOException e) {System.err.println("File Error");;System.exit(1);}}}cs 'Computer Science > Data Structure' 카테고리의 다른 글
Graph - DFS(Depth First Search) 구현 (0) 2021.05.24 Data Structure - 우선순위 큐(priority queue), 힙(heap) (0) 2021.03.02 Data Structure-Tree(Vol.2), <이진 탐색 트리> 탐색, 삽입, 삭제, 분석 (0) 2021.02.25 Data Structure - Tree(Vol.1), (자료구조-트리) (0) 2021.02.23 Data Structure - linked list(Vol.2), (자료 구조-연결 리스트) (0) 2021.02.18 댓글