๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

[Algorithm/Java][๋ฐฑ์ค€] 1987๋ฒˆ ์•ŒํŒŒ๋ฒณ

๋ฐ˜์‘ํ˜•

[BOJ] 1987๋ฒˆ ์•ŒํŒŒ๋ฒณ

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

๋ฌธ์ œ ์ ‘๊ทผ

๊ฐ€๋กœ R, ์„ธ๋กœ C๋กœ ๋œ ๋ณด๋“œ์— ๋Œ€๋ฌธ์ž ์•ŒํŒŒ๋ฒณ์ด ์ ํ˜€์žˆ๊ณ , ๊ฐ€์žฅ ์™ผ์ชฝ ์œ„๋ถ€ํ„ฐ ์•ŒํŒŒ๋ฒณ ๋‹น ํ•œ๋ฒˆ์”ฉ๋งŒ ๋ฐฉ๋ฌธํ•ด์„œ ๊ฐ€์žฅ ๋ฉ€๋ฆฌ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๊ธธ์ด๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.
์ฒ˜์Œ์—๋Š” ์•„๋ฌด์ƒ๊ฐ ์—†์ด bfs๋กœ ํ–ˆ๋‹ค๊ฐ€ ์ƒ๊ฐํ•ด๋ณด๋‹ˆ๊นŒ dfs๊ฐ€ ๋” ๋งž๋Š” ๊ฒƒ ๊ฐ™์•„์„œ ๋ฐฉํ–ฅ์„ ํ‹€์—ˆ๋‹ค.
์ฒ˜์Œ์—๋Š” ๋ณด๋“œ์— ๋ฐฉ๋ฌธ ์—ฌ๋ถ€๋ฅผ ์ €์žฅํ•˜๋Š” isVisited์™€ ์•ŒํŒŒ๋ฒณ ๋ฐฉ๋ฌธ ์—ฌ๋ถ€๋ฅผ ์ €์žฅํ•˜๋Š” alphabetVisited๋ฅผ ์‚ฌ์šฉํ•˜๋ ค ํ–ˆ๋Š”๋ฐ, ์ƒ๊ฐํ•ด๋ณด๋‹ˆ๊นŒ ํ•œ๋ฒˆ ๋ฐฉ๋ฌธํ•œ ์•ŒํŒŒ๋ฒณ์€ ๋ฐฉ๋ฌธํ•˜์ง€ ๋ชปํ•˜๋‹ˆ๊นŒ ๋ณด๋“œ์— ๋ฐฉ๋ฌธ์—ฌ๋ถ€๋ฅผ ์ €์žฅํ•  ํ•„์š”๊ฐ€ ์—†๊ณ , ๊ฒฝ๋กœ๋ฅผ String์œผ๋กœ ๊ณ„์† ์ถ”๊ฐ€ํ•ด๊ฐ€๋ฉด์„œ ํ•˜๋ฉด ์•ŒํŒŒ๋ฒณ ๋ฐฉ๋ฌธ ์—ฌ๋ถ€๋„ ๋”ฐ๋กœ ์ €์žฅํ•˜์ง€ ์•Š์•„๋„ ๋  ๊ฒƒ ๊ฐ™์•„์„œ dfs์— ๊ฐ€๋ ค๋Š” x,y์™€ ์ง€๊ธˆ๊นŒ์ง€์˜ ๊ฒฝ๋กœ๋ฅผ ๋‹ด์€ path๋ฅผ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœํ•ด์„œ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜์˜€๋‹ค.

Code

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

public class BOJ1987 {
    static int[] dx = {1, -1, 0, 0};
    static int[] dy = {0, 0, -1, 1};
    static char[][] alphabet;
    static int R,C;
    static int answer = 0;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] s = br.readLine().split(" ");
        R = Integer.parseInt(s[0]);
        C = Integer.parseInt(s[1]);
        alphabet = new char[R][C];
        for(int i = 0; i<R; i++){
            alphabet[i] = br.readLine().toCharArray();
        }
        dfs(0, 0, String.valueOf(alphabet[0][0]));
        System.out.println(answer);
    }
    public static void dfs(int x, int y, String path) {
        answer = Math.max(answer,path.length());
        for(int i = 0; i<4; i++){
            int next_x = x + dx[i];
            int next_y = y + dy[i];
            if(isIn(next_x,next_y)) continue;
            if(path.indexOf(alphabet[next_x][next_y]) != -1) continue;
            dfs(next_x, next_y, path+alphabet[next_x][next_y]);
        }
    }
    public static boolean isIn(int x, int y){
        return x<0 || x >= R || y<0 || y>=C;
    }

}
๋ฐ˜์‘ํ˜•