패스트캠퍼스 챌린지 12일차
탐색 알고리즘
• 순차 탐색 (Sequential Search)
- 데이터가 담겨있는 리스트를 앞에서 부터 하나씩 비교하여 원하는 데이터를 찾는 알고리즘
public class SequencialSearch{
public int searchFunc(ArrayList<Integer> dataList, Integer searchItem){
for(int index = 0; index < dataList.size(); index++){
if(dataList.get(index) == searchItem){
return index;
}
}
return -1;
}
}
최악의 경우 리스트 길이가 n일 떄, n번 비교 => 시간복잡도 : O(n)
• 이진 탐색 (Binary Search)
- 탐색할 자료들을 둘로 나누어 해당 데이터가 있을만한 곳을 탐색하는 방법
public class BinarySearch{
public boolean searchFunc(ArrayList<Integer> dataList, Integer searchItem){
if(dataList.size() == 1 && searchItem == dataList.get(0)){
return true;
}
if(dataList.size() == 0){
return false;
}
int medium = dataList.size() / 2;
if(searchItem = dataList.get(medium)){
return true;
}else{
if(searchItem < dataList.get(medium)){
return this.searchFunc(new ArrayList<Integer>(dataList.subList(0,medium)),searchItem);
}else{
return this.searchFunc(new ArrayList<Integer>(dataList.subList(medium,dataList.size())),searchItem);
}
}
}
}
n개의 리스트를 매번 2로 나누어 1이 될 때까지 비교 연산 k회를 진행 => 시간 복잡도 O(logn)
그래프 (Graph)
- 실제 세계의 현상이나 사물을 정점(Vertex) 또는 노드(Node)와 간선(Edge)로 표현하기 위해 사용
관련 용어
- 정점(Vertex) : 위치를 뜻함, 노드(Node)라고도 한다.
- 간선(Edge) : 위치 간의 관계를 표시한 선, vertex를 연결한 선이다. link, branch 라고도 한다.
- 인접 정점(Adjacent Vertex) : Edge로 직접 연결된 Vertex
- 정점의 차수(Degree): 무방향 그래프에서 하나의 정점에 인접한 정점의 수
- 진입 차수(In-Degree): 방향 그래프에서 외부에서 오는 간선의 수
- 진출 차수(Out-Degree): 방향 그래프에서 외부로 향하는 간선의 수
- 경로 길이(Path Length): 경로를 구성하기 위해 사용된 간선의 수
- 단순 경로(Simple Path): 처음 정점과 끝 정점을 제외하고 중복된 정점이 없는 경로
- 사이클(Cycle): 단순 경로의 시작 정점과 종료 정점이 동일한 경우
종류
• 무방향 그래프 (Undirected Graph)
- 방향이 없는 그래프
- 간선을 통해, 정점은 양방향으로 갈 수 있다
- 표기 방법 : Vertex A, B가 연결 되어 있을 경우 (A,B) or (B,A)
• 방향 그래프 (Directed Graph)
- 간선에 방향이 있는 그래프
- 표기 방법 : Vertex A -> B로 연결 되어 있을 경우 <A,B>
• 가중치 그래프 (Weighted Graph)
- 간선에 비용 또는 가중치가 할당된 그래프
• 연결 그래프 (Connected Graph)
- 무방향 그래프에 모든 정점에 대해 항상 경로가 존재하는 경우
• 비연결 그래프 (DIsconnected Graph)
- 무방향 그래프에 특정 정점에 대해 경로가 존재하지 않는 경우
• 사이클 (Cycle)
- 단순 경로의 시작 정잠과 종료 정점이 동일한 경우
• 비순환 그래프(Acyclic Graph)
- 사이클이 없는 그래프
• 완전 그래프(Complete Graph)
- 그래프의 모든 정점이 서로 연결되어 있는 그래프
그래프 기본 탐색 알고리즘
• 너비 우선 탐색 (Breadth-First Search, BFS)
- 한 단계씩 내려가면서, 해당 노드(정점)와 같은 레벨에 있는 노드(형제 노드)을 먼저 순회
EX ) 그래프에서 노드(정점)을 key, 간선으로 이어진 모든 노드들을 values로 저장
key | values | |||
A | B | C | ||
B | A | D | ||
C | A | |||
D | B | E | ||
E | D |
HashMap<String, ArrayList<String>> graph = new HashMap<String,ArrayList<String>>();
- 방문한 Queue, 방문이 필요한 Queue, 두 개의 Queue를 사용하여 구현한다.
import java.util.ArrayList;
import java.util.HashMap;
public class BFSSearch {
public ArrayList<String> bfsFunc(HashMap<String, ArrayList<String>> grpah, String startNode) {
ArrayList<String> visited = new ArrayList<String>();
ArrayList<String> needVisit = new ArrayList<String>();
needVisit.add(startNode);
while (needVisit.size() > 0) {
String node = needVisit.remove(0);
if (!visited.contains(node)) {
visited.add(node); // node는 revmove한 값을 가지고 있다.
needVisit.addAll(graph.get(node)); // EX) graph.get(node) = ["B","C"]
}
}
return visited;
}
}
시간 복잡도
- 노드 수 : V
- 간선 수 : E
=> O(V+E) 로 표현
• 깊이 우선 탐색 (Depth-First Search, DFS)
- 한 노드(정점)의 자식을 타고 끝가지 순회한 후, 다시 돌아와 다른 형제들의 자식을 타고 내려가며 순회
- 방문할 스택과, 방문한 큐를 활용
public class DFSSearch {
public ArrayList<String> dfsFunc(HashMap<String, ArrayList<String>> graph, String startNode) {
ArrayList<String> visited = new ArrayList<String>();
ArrayList<String> needVisit = new ArrayList<String>();
needVisit.add(startNode);
while (needVisit.size() > 0) {
String node = needVisit.remove(needVisit.size() - 1); // BFS와 이 부분만 다름 (큐 -> 스택)
if (!visited.contains(node)) {
visited.add(node);
needVisit.addAll(graph.get(node));
}
}
return visited;
}
}
시간 복잡도
- 노드 수 : V
- 간선 수 : E
=> O(V+E) 로 표현
본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.
https://bit.ly/37BpXiC
패스트캠퍼스 [직장인 실무교육]
프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.
fastcampus.co.kr