[Algorithm /백준] 1987 알파벳

2024. 1. 14. 12:30Algorithm/JAVA

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

말은 상하좌우로 인접한 네 칸 중의 한 칸으로 이동할 수 있는데, 새로 이동한 칸에 적혀 있는 알파벳은 지금까지 지나온 모든 칸에 적혀 있는 알파벳과는 달라야 한다. 즉, 같은 알파벳이 적힌 칸을 두 번 지날 수 없다.

좌측 상단에서 시작해서, 말이 최대한 몇 칸을 지날 수 있는지를 구하는 프로그램을 작성하시오. 말이 지나는 칸은 좌측 상단의 칸도 포함된다.

[입력]
첫째 줄에 R과 C가 빈칸을 사이에 두고 주어진다. (1 ≤ R,C ≤ 20) 둘째 줄부터 R개의 줄에 걸쳐서 보드에 적혀 있는 C개의 대문자 알파벳들이 빈칸 없이 주어진다.

[출력]
첫째 줄에 말이 지날 수 있는 최대의 칸 수를 출력한다.

[문제 해결 - DFS, 백트래킹]

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main{

    static String[][] arr;
    static boolean[] visited;
    static int[] dx = {0, 1, 0, -1};
    static int[] dy = {1, 0, -1, 0};
    static int maxCount = 1; // 시작점은 무조건 포함

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String[] input = br.readLine().split(" ");
        int R = Integer.parseInt(input[0]);
        int C = Integer.parseInt(input[1]);

        arr = new String[R][C];
        visited = new boolean[26]; // 알파벳 개수만큼 방문 여부를 체크

        for (int i = 0; i < R; i++) {
            String line = br.readLine();
            for (int j = 0; j < C; j++) {
                arr[i][j] = line.substring(j, j + 1);
            }
        }

        visited[arr[0][0].charAt(0) - 'A'] = true; // 시작 지점 방문 표시
        DFS(0, 0, 1); // 시작점은 무조건 포함

        System.out.println(maxCount);
        br.close();
    }

    public static void DFS(int x, int y, int count) {
        maxCount = Math.max(maxCount, count);

        for (int i = 0; i < 4; i++) {
            int newX = x + dx[i];
            int newY = y + dy[i];

            if (newX >= 0 && newX < arr.length && newY >= 0 && newY < arr[0].length
                    && !visited[arr[newX][newY].charAt(0) - 'A']) {
                visited[arr[newX][newY].charAt(0) - 'A'] = true;
                DFS(newX, newY, count + 1);
                visited[arr[newX][newY].charAt(0) - 'A'] = false; // 백트래킹
            }
        }
    }
}