트리나 그래프를 탐색하는 기법 중 하나로, 루트 노드(혹은 다른 임의의 노드)에서 시작해서 인접한 노드를 먼저 탐색하는 방법으로 깊게 탐색하기 전에 넓게 탐색하는 것이다.
- 두 노드 사이의 최단 경로 혹은 임의의 경로를 찾고 싶을 때 사용한다.
- 미로 찾기 등 최단 거리를 구해야 할 경우 사용된다.
public class Bfs {
static Map<Integer, List<Integer>> graph = new HashMap<>(); // 그래프를 인접 리스트로 표현
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
graph.put(1, Arrays.asList(2,3));
graph.put(2, Arrays.asList(4,5));
graph.put(3, Arrays.asList(6,7));
graph.put(4, Collections.emptyList());
graph.put(5, Collections.emptyList());
graph.put(6, Collections.emptyList());
graph.put(7, Collections.emptyList());
bfs(1);
System.out.println(sb);
}
static void bfs(int start) {
Queue<Integer> queue = new LinkedList<>();
boolean[] visited = new boolean[graph.size()+1];
queue.offer(start);
visited[start] = true;
while (!queue.isEmpty()) {
int node = queue.poll();
sb.append(node).append(" ");
List<Integer> neighbors = graph.getOrDefault(node, new ArrayList<>());
for(int neighbor : neighbors) {
if(!visited[neighbor]) {
queue.offer(neighbor);
visited[neighbor] = true;
}
}
}
}
}
(노드 수 : N, 엣지 수 : E)
인접 리스트
인접 행렬
