백준 - 1987 - 알파벳

2021. 3. 25. 14:44Algorithm

www.acmicpc.net/problem/1987

 

1987번: 알파벳

세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이 놓여 있다. 말은 상하좌우로 인접한 네 칸 중의 한 칸으

www.acmicpc.net

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
 
/**
 * 백준 - 1987
 * 2 4
 * CAAB
 * ADCB
 */
public class Main {
    private static int R;
    private static int C;
    private static Set<String> isVisit = new HashSet<>();
    private static String[][] map;
    private static int maxCount = 0;
    private static int[][] directions = new int[][]{{-1,0},{0,1},{1,0},{0,-1}};// 위, 오른쪽, 아래, 왼쪽
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] inputs = sc.nextLine().split(" ");
        R = Integer.parseInt(inputs[0]);
        C = Integer.parseInt(inputs[1]);
        map = new String[R][C];
        for(int i=0; i<R; i++) {
            map[i] = sc.nextLine().split("");
        }
        isVisit.add(map[0][0]);
        dfs(001);
        System.out.println(maxCount);
    }
 
    private static void dfs(int x, int y, int count) {
        if(maxCount < count) {
            maxCount = count;
        }
 
        for(int[] direction : directions) {
            int nextX = x + direction[0];
            int nextY = y + direction[1];
            if(0 <= nextX && nextX < R && 0 <= nextY && nextY < C && !isVisit.contains(map[nextX][nextY])) {
                isVisit.add(map[nextX][nextY]);
                count++;
                dfs(nextX, nextY, count);
                count--;
                isVisit.remove(map[nextX][nextY]);
            }
        }
    }
}
cs

알고리즘

  • DFS
  • 깊이우선탐색으로 가장 깊게 갈 수 있는 경로를 찾으면 된다.
  • Set을 이용하여 방문한 문자인지 판단할 수 있다.

'Algorithm' 카테고리의 다른 글

백준 - 1697 - 숨바꼭질  (0) 2021.03.26
백준 - 2644 - 촌수계산  (0) 2021.03.25
백준 - 1759 - 암호 만들기  (0) 2021.03.23
백준 - 6603 - 로또  (0) 2021.03.23
프로그래머스 - 힙 - 이중우선순위큐  (0) 2021.03.23