문제 풀이/백준

[백준] 1987번. 알파벳 (JAVA)

27200 2024. 2. 14. 22:12

https://www.acmicpc.net/problem/1987


문제


풀이

import java.io.*;
import java.util.*;
public class Main {

    static int R, C;
    static int[][] map;
    static boolean[] visit = new boolean[26];
    static int[] dx = {0, 1, 0, -1};
    static int[] dy = {1, 0, -1, 0};
    static int ans = 0;


    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        R = Integer.parseInt(st.nextToken());
        C = Integer.parseInt(st.nextToken());
        map = new int[R][C];
        for (int i = 0; i < R; i++) {
            String str = br.readLine();
            for (int j = 0; j < C; j++) {
                map[i][j] = str.charAt(j) - 'A';
            }
        }

        dfs(0, 0, 1);

        System.out.println(ans);
    }

    public static void dfs(int i, int j, int count) {
        ans = Math.max(ans, count);
        visit[map[i][j]] = true;
        for (int x = 0; x < 4; x++) {
            int cx = i + dx[x];
            int cy = j + dy[x];
            if (cx >= 0 && cy >= 0 && cx < R && cy < C) {
                if(!visit[map[cx][cy]]){
                    dfs(cx, cy, count + 1);
                    visit[map[cx][cy]] = false;
                }
            }

        }
    }
}

문제를 따라가며 알파벳의 확인 여부를 체크하고 다시 올라올 때는 이를 해제하며 올라오는 방식을 택하여 문제를 해결하면 된다.