1. DFS/BFS란?
1-1. 그래프
DFS/BFS에 대해 이해하려면 먼저 그래프의 기본 구조를 알아야한다.
그래프는 노드(Node)와 간선(Edge)으로 표현되며 이 때 노드를 정점(Vertex)라고 말한다.
그래프 탐색이란 하나의 노드를 시작으로 다수의 노드를 방문하는 것을 말하며 두 노드가 간선으로 연결되어 있을 때 ‘인접하다’고 표현한다.
그래프는 크게 2가지 방식으로 표현할 수 있다.
- 인접 행렬(Adjacency Matrix)
- 인접 리스트(Adjacency List)
먼저 인접 행렬 방식은 2차원 배열에 각 노드가 연결된 형태를 기록하는 방식이다.
인접 리스트 방식은 모든 노드에 연결된 노드에 대한 정보를 차례대로 연결해서 저장한다.
인접 행렬 방식은 노드 개수가 많을수록 메모리가 불필요하게 낭비되는 반면 인접 리스트 방식은 메모리를 효율적으로 사용한다. 하지만 이와 같은 속성 때문에 인접 리스트 방식은 두 노드가 연결되어 있는지에 대한 정보를 얻는 속도가 느리다.
1-2. DFS
DFS는 Depth First Search, 깊이 우선 탐색이라고 부르며 그래프에서 깊은 부분을 우선적으로 탐색하는 알고리즘이다.
이 그래프에서 노드 1부터 시작해서 DFS를 이용한 탐색을 진행해보자.
방문 순서 : 1 → 2 → 7 → 6 → 8 → 3 → 4 → 5
1-3. BFS
BFS는 Breadth First Search, 너비 우선 탐색이라고 부르며 가까운 노드부터 탐색하는 알고리즘이다.
DFS와 같은 상황을 가지고 BFS를 이용한 탐색을 해보자.
방문 순서 : 1 → 2 → 3 → 8 → 7 → 4 → 5 → 6
2. 예제
💡 모든 문제는 나동빈 저자의 “이것이 코딩테스트다”에 수록되어 있으며 작성한 코드는 오류가 있을 수도 있음을 미리 밝힙니다.
2-1. 음료수 얼려 먹기
문제
N X M 크기의 얼음 틀이 있다. 구멍이 뚫려 있는 부분은 0, 칸막이가 존재하는 부분은 1로 표시된다.
구멍이 뚫려 있는 부분끼리 상, 하, 좌, 우로 붙어 있는 경우 서로 연결되어 있는 것으로 간주한다. 이 때 얼음 틀의 모양이 주어졌을 때 생성되는 총 아이스크림의 개수를 구하는 프로그램을 작성하시오.
다음의 4 X 5 얼음 틀 예시에서는 아이스크림이 총 3개 생성된다.
00110
00011
11111
00000
입력
- 첫 번째 줄에 얼음 틀의 세로 길이 N과 가로 길이 M이 주어진다.
- 두 번째 줄부터 N + 1번째 줄까지 얼음 틀의 형태가 주어진다.
- 이 때 구멍이 뚫려 있는 부분은 0, 그렇지 않은 부분은 1이다.
출력
- 한 번에 만들 수 있는 아이스크림의 개수를 출력한다.
입력 예시
15 14
00000111100000
11111101111110
11011101101110
11011101100000
11011111111111
11011111111100
11000000011111
01111111111111
00000000011111
01111111111000
00011111111000
00000001111000
11111111110011
11100011111111
11100011111111
출력 예시
8
코드(BFS)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static boolean[][] visited;
static int[][] arr;
static int row;
static int column;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
row = Integer.parseInt(st.nextToken());
column = Integer.parseInt(st.nextToken());
visited = new boolean[row][column];
arr = new int[row][column];
for(int i=0; i<row; i++) {
String s = br.readLine();
for(int k=0; k<column; k++) {
arr[i][k] = s.charAt(k)-'0';
}
}
int count = 0;
for(int i=0; i<row; i++) {
for(int k=0; k<column; k++) {
if(!visited[i][k] && arr[i][k]==0) {
bfs(i, k);
count++;
}
}
}
System.out.println(count);
}
static void bfs(int num1, int num2) {
Queue<int[]> qu = new LinkedList<>();
int[] dx = {-1, 1, 0, 0};
int[] dy = {0, 0, 1, -1};
qu.add(new int[]{num1, num2});
visited[num1][num2] = true;
while(!qu.isEmpty()) {
int[] start = qu.poll();
for(int i=0; i<4; i++) {
int nextX = start[0] + dx[i];
int nextY = start[1] + dy[i];
if(nextX>=0 && nextY >=0 && nextX < row && nextY < column) {
if(!visited[nextX][nextY] && arr[nextX][nextY]==0) {
qu.add(new int[]{nextX, nextY});
visited[nextX][nextY] = true;
}
}
}
}
}
}
코드(DFS)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static boolean[][] visited;
static int[][] arr;
static int row;
static int column;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
row = Integer.parseInt(st.nextToken());
column = Integer.parseInt(st.nextToken());
visited = new boolean[row][column];
arr = new int[row][column];
for(int i=0; i<row; i++) {
String s = br.readLine();
for(int k=0; k<column; k++) {
arr[i][k] = s.charAt(k)-'0';
}
}
int count = 0;
for(int i=0; i<row; i++) {
for(int k=0; k<column; k++) {
if(!visited[i][k] && arr[i][k]==0) {
dfs(i, k);
count++;
}
}
}
System.out.println(count);
}
static void dfs(int num1, int num2) {
int[] dx = {-1, 1, 0, 0};
int[] dy = {0, 0, 1, -1};
for(int i=0; i<4; i++) {
int nextX = num1 + dx[i];
int nextY = num2 + dy[i];
if(nextX>=0 && nextY >=0 && nextX < row && nextY < column) {
if(!visited[nextX][nextY] && arr[nextX][nextY]==0) {
visited[nextX][nextY] = true;
dfs(nextX, nextY);
}
}
}
}
2-2. 미로 탈출
문제
동빈이는 N X M 크기의 직사각형 형태의 미로에 갇혀 있다. 미로에는 여러 마리의 괴물이 있어 이를 피해 탈출해야 한다. 동빈이의 위치는 (1, 1)이고 미로의 출구는 (N, M)의 위치에 존재하며 한 번에 한 칸씩 이동할 수 있다. 이 때 괴물이 있는 부분은 0으로 괴물이 없는 부분은 1로 표시되어 있다. 미로는 반드시 탈출할 수 있는 형태로 제시된다. 이 때 동빈이가 탈출하기 위해 움직여야 하는 최소 칸의 개수를 구하시오. 칸을 셀 때는 시작 칸과 마지막 칸을 모두 포함해서 계산한다.
입력
- 첫째 줄에 두 정수 N, M(4 ≤ N, M ≤ 200)이 주어집니다.
- 다음 N개의 줄에는 각각 M개의 정수(0 혹은 1)로 미로의 정보가 주어진다. 각각의 수들은 공백 없이 붙어서 입력으로 제시된다.
- 또한 시작 칸과 마지막 칸은 항상 1이다.
출력
- 첫째 줄에 최소 이동 칸의 개수를 출력한다.
입력 예시
5 6
101010
111111
000001
111111
111111
출력 예시
10
코드(BFS)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static boolean[][] visited;
static int[][] arr;
static int row;
static int column;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
row = Integer.parseInt(st.nextToken());
column = Integer.parseInt(st.nextToken());
visited = new boolean[row][column];
arr = new int[row][column];
for(int i=0; i<row; i++) {
String s = br.readLine();
for(int k=0; k<column; k++) {
arr[i][k] = s.charAt(k)-'0';
}
}
bfs();
int result = arr[row-1][column-1];
System.out.println(result);
}
static void bfs() {
Queue<int[]> qu = new LinkedList<>();
int[] dx = {-1, 1, 0, 0};
int[] dy = {0, 0, 1, -1};
qu.add(new int[]{0, 0});
visited[0][0] = true;
while(!qu.isEmpty()) {
int[] start = qu.poll();
for(int i=0; i<4; i++) {
int nextX = start[0] + dx[i];
int nextY = start[1] + dy[i];
if(nextX>=0 && nextY >=0 && nextX < row && nextY < column) {
if(!visited[nextX][nextY] && arr[nextX][nextY]==1) {
qu.add(new int[]{nextX, nextY});
visited[nextX][nextY] = true;
arr[nextX][nextY] = arr[start[0]][start[1]]+1;
}
}
}
}
}
}
'CS > Algorithm' 카테고리의 다른 글
구현(Implementation Algorithm) (0) | 2023.04.04 |
---|---|
그리디(Greedy) 알고리즘 (0) | 2023.03.30 |