/
BAEKJOON 1987
42 lines (34 loc) · 1.08 KB
/
BAEKJOON 1987
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static char[][] map;
static boolean[] select = new boolean[26];
static int R, C, ans = Integer.MIN_VALUE;
static int[] dy = { -1, 1, 0, 0 }, dx = { 0, 0, -1, 1 };
public static void main(String[] args) throws Exception {
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 char[R][];
for (int i = 0; i < R; i++) {
map[i] = br.readLine().toCharArray();
}
select[map[0][0] - 'A'] = true;
DFS(0, 0, 1);
System.out.println(ans);
}
private static void DFS(int y, int x, int cnt) {
ans = Math.max(ans, cnt);
for (int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (ny < 0 || nx < 0 || ny >= R || nx >= C || select[map[ny][nx] - 'A'])
continue;
select[map[ny][nx] - 'A'] = true;
DFS(ny, nx, cnt+1);
select[map[ny][nx] - 'A'] = false;
}
}
}