1 minute read

๐Ÿ“Œ ๋‚œ์ด๋„

๐Ÿฅ‡ Gold 4


๐Ÿ“Œ ๋ฌธ์ œ

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

image

image


๐Ÿ“Œ ํ’€์ด

๋ชจ๋“  ๋ฌธ์ œ๋ฅผ BFS๋กœ ํ’€ ์ˆ˜ ์žˆ๋‹ค๊ณ  ์ž์‹ ๋งŒ๋งŒํ•˜๋˜ ๋•Œ์— ์ •์‹ ์ ์ธ ์ถฉ๊ฒฉ์„ ์ค€ ๋ฌธ์ œ์˜€๋‹ค.
BFS๋กœ ์ด ๋ฌธ์ œ๋ฅผ ๊ตฌํ˜„ํ•˜๋ ค๋ฉด ์ค‘๋ณต์ด ๋„ˆ๋ฌด๋‚˜๋„ ๋งŽ์ด ๋ฐœ์ƒํ•˜์—ฌ, ๋ฉ”๋ชจ๋ฆฌ์ดˆ๊ณผ๊ฐ€ ๋œฐ ์ˆ˜ ๋ฐ–์— ์—†๋Š” ๋ฌธ์ œ์˜€๋‹ค.
๋”ฐ๋ผ์„œ, ์ฒ˜์Œ์œผ๋กœ ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ DFS๋ฅผ ๊ตฌํ˜„ํ•ด ๋ณด์•˜๋‹ค.


๐Ÿ“Œ Code

package BOJ.DFS;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Stack;
import java.util.StringTokenizer;

public class N1987 {
    static int R;
    static int C;
    static int[][] board;
    static boolean[] visited;
    static final int[] DR = {-1, 0, 1, 0};
    static final int[] DC = {0, 1, 0, -1};
    static int max;

    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());
        board = new int[R][C];
        visited = new boolean[26];
        for (int i = 0; i < R; i++) {
            String str = br.readLine();
            for (int j = 0; j < C; j++) {
                board[i][j] = str.charAt(j) - 'A';
            }
        }
        max = 0;
        DFS(0, 0, 0);
        System.out.println(max);
    }

    static void DFS(int r, int c, int count) {
        if (visited[board[r][c]]) {
            max = Math.max(max, count);
            return;
        } else {
            visited[board[r][c]] = true;
            for (int i = 0; i < DR.length; i++) {
                int nextR = r + DR[i];
                int nextC = c + DC[i];
                if (nextR < 0 || nextR >= R || nextC < 0 || nextC >= C) {
                    continue;
                }
                DFS(nextR, nextC, count + 1);
            }
            visited[board[r][c]] = false;
        }
    }
}

package (์ด๋ฆ„); ๋ฅผ ๋•Œ๊ณ , class ์ด๋ฆ„์„ Main์œผ๋กœ ๋ณ€๊ฒฝํ•˜๋ฉด ๋œ๋‹ค.



๊ฐœ์ธ ๊ณต๋ถ€ ๊ธฐ๋ก์šฉ ๋ธ”๋กœ๊ทธ์ž…๋‹ˆ๋‹ค.
ํ‹€๋ฆฌ๊ฑฐ๋‚˜ ์˜ค๋ฅ˜๊ฐ€ ์žˆ์„ ๊ฒฝ์šฐ ์ œ๋ณดํ•ด์ฃผ์‹œ๋ฉด ๊ฐ์‚ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.๐Ÿ˜