https://www.acmicpc.net/problem/1987
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class BOJ_1987 {
static int R, C;
static char[][] map;
static int[] dx = { 0, -1, 0, 1 };
static int[] dy = { -1, 0, 1, 0 };
static boolean[] visited;
static int total;
static int max=Integer.MIN_VALUE;
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 char[R][C];
for (int i = 0; i < R; i++) {
map[i] = br.readLine().toCharArray();
}
visited = new boolean[26];
total=0;
visited[map[0][0]-65]=true;
find(0, 0,1);
System.out.println(max);
}
private static void find(int x, int y, int cnt) {
max=Math.max(max, cnt);
for(int i=0;i<4;i++) {
int nx=x+dx[i];
int ny=y+dy[i];
if (0 <= nx && nx < R && 0 <= ny && ny < C) {
int c=map[nx][ny];
if(!visited[c-65]) {
visited[c-65]=true;
find(nx, ny, cnt+1);
visited[c-65]=false;
}
}
}
}
}