https://www.acmicpc.net/problem/1987
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main{
static int[][] arr;
static boolean[] alpha;
static int[] dx = {-1, 0, 1, 0};
static int[] dy = {0, 1, 0, -1};
static int r, c;
static int answer = 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());
arr = new int[r][c];
alpha = new boolean[26];
for(int i=0; i<r; i++){
String str = br.readLine();
for(int j=0; j<c; j++){
arr[i][j] = str.charAt(j)-65;
}
}
alpha[arr[0][0]] = true;
dfs(0, 0, 1);
System.out.println(answer);
}
static void dfs(int x, int y, int cnt) {
answer = Math.max(answer, cnt);
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || nx >= r || ny < 0 || ny >= c || alpha[arr[nx][ny]]) continue;
alpha[arr[nx][ny]] = true; // 나온 알파벳으로 체크
dfs(nx, ny, cnt + 1);
alpha[arr[nx][ny]] = false; // 복구
}
}
}
'ALGORITHM' 카테고리의 다른 글
[JAVA] 백준 1697번- 숨바꼭질 (0) | 2023.01.09 |
---|---|
[JAVA] 백준 1707번- 이분 그래프 (0) | 2023.01.06 |
[JAVA] 백준 2580번- 스도쿠 (0) | 2023.01.06 |
[JAVA] 백준 16198번- 에너지 모으기 (0) | 2023.01.04 |
[JAVA] 백준 9663번- N-Queen (0) | 2023.01.04 |