Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- concurrency limit
- Dev-Matching
- 검색
- this
- 파일 url
- 프론트엔드
- 모던 자바스크립트
- 스프링부트
- 딥다이브
- bucket4j
- TypeORM
- 자바스크립트
- 타입스크립트
- 우아한 테크코스
- compateto
- api 요청 수 제한
- Deep Dive
- 유효시간 설정 url
- NestJS
- 프로그래머스
- invalid_grant
- 프론트엔드 과제
- 프리코스
- api 비동기처리
- redis
- oauth
- AWS
- 코멘토 #코멘토실무PT #실무PT후기 #실무강의 #리액트강의 #웹프로그래밍 #react #웹개발실무
- 음악 url 파일 다운로드
- 우아한테크코스
Archives
- Today
- Total
개발 알다가도 모르겠네요
BFS (너비 우선 탐색) 를 간단하게 알아보자. 본문
728x90
BFS(Breath First Search)를 간단하게 설명하면?
그래프에서 가까운 노드부터 우선적으로 탐색하는 알고리즘!
시작 정점부터 가까운 정점을 먼저 방문하고 멀리 떨어져 있는 정점을 나중에 방문하는 순회 방법입니다.
큐를 이용하여 구현을 합니다.
- 탐색 시작 노드를 큐에 삽입하고 방문 처리를 합니다.
- 큐에서 노드를 꺼낸 뒤에 해당 노드의 인접 노드 중에서 방문하지 않은 노드를 모두 큐에 삽입하고 방문 처리합니다.
- 위의 과정을 수행할 수 없을 때까지 반복합니다.
BFS 구현 과정
인접리스트
import java.util.*;
public class Main {
public static boolean visited[];
public static int v;
public static int e;
public static ArrayList<ArrayList<Integer>> graph;
public static void bfs(int start) {
Queue <Integer> q = new <Integer> LinkedList();
q.offer(start); //첫 정점노드 삽입
visited[start] = true;
while(!q.isEmpty()) { //큐가 빌 때까지
int a = q.poll();
System.out.print(a+" ");
for(int i=0; i < graph.get(a).size(); i++) {
int b = graph.get(a).get(i);
if(!visited[b]) {
q.offer(b);
visited[b]= true;
}
}
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
v = scan.nextInt();
e = scan.nextInt();
graph = new ArrayList<ArrayList<Integer>>(v+1);
visited = new boolean[v+1];
for(int i=0; i<e; i++) {
graph.add(new ArrayList());
int t1 = scan.nextInt();
int t2 = scan.nextInt();
graph.get(t1).add(t2);
graph.get(t2).add(t1);
}
bfs(1);
}
}
인접 행렬
import java.util.*;
public class Main {
public static boolean visited[];
public static int v;
public static int e;
public static int[][] graph; //인접 행렬
public static void bfs(int start) {
Queue <Integer> q = new <Integer> LinkedList();
q.offer(start);
visited[start] = true;
while(!q.isEmpty()) {
int a = q.poll();
System.out.print(a+" ");
for(int i=1; i<=v; i++) {
if(graph[a][i] ==1 && visited[i]==false) { //노드값이 1이고, 방문하지 않았다면
q.offer(i);
visited[i]= true;
}
}
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
v = scan.nextInt();
e = scan.nextInt();
graph = new int[v+1][v+1];
visited = new boolean[v+1];
for(int i=0; i<e; i++) {
int t1 = scan.nextInt();
int t2 = scan.nextInt();
graph[t1][t2] = 1;
graph[t2][t1] = 1;
}
bfs(1);
}
}
시간 복잡도
V: 정점
E: 간선
- 인접 리스트 : O(V + E)
- 인접 행렬 : O(V^2)
'자료구조 > 그래프' 카테고리의 다른 글
이분 그래프 (Bipartite Graph) 를 간단하게 알아보자. (0) | 2021.01.17 |
---|---|
DFS & BFS 특 (0) | 2021.01.15 |
DFS (깊이 우선 탐색) 를 간단하게 알아보자. (0) | 2021.01.14 |