|
| 1 | +package DFS.P1987; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | +import java.util.StringTokenizer; |
| 5 | + |
| 6 | +public class Main { |
| 7 | + |
| 8 | + static int R, C, max; |
| 9 | + static char[][] map; |
| 10 | + static boolean[] visited = new boolean[26]; |
| 11 | + |
| 12 | + static int[] di = {-1, 0, 1, 0}; |
| 13 | + static int[] dj = {0, 1, 0, -1}; |
| 14 | + |
| 15 | + public static void main(String[] args) throws Exception { |
| 16 | + System.setIn(new FileInputStream("src/DFS/P1987/input.txt")); |
| 17 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 18 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 19 | + |
| 20 | + R = Integer.parseInt(st.nextToken()); |
| 21 | + C = Integer.parseInt(st.nextToken()); |
| 22 | + |
| 23 | + map = new char[R][C]; |
| 24 | + for (int i = 0; i < R; i++) map[i] = br.readLine().toCharArray(); |
| 25 | + |
| 26 | + visited[map[0][0]-'A'] = true; |
| 27 | + dfs(0, 0, 1); |
| 28 | + System.out.println(max); |
| 29 | + } |
| 30 | + |
| 31 | + static void dfs(int i, int j, int cnt) { |
| 32 | + for (int t = 0; t < 4; t++) { |
| 33 | + int to_i = i + di[t]; |
| 34 | + int to_j = j + dj[t]; |
| 35 | + |
| 36 | + if (isValidPath(to_i, to_j) && !visited[map[to_i][to_j]-'A']) { |
| 37 | + visited[map[to_i][to_j]-'A'] = true; |
| 38 | + dfs(to_i, to_j, cnt+1); |
| 39 | + visited[map[to_i][to_j]-'A'] = false; |
| 40 | + } |
| 41 | + } |
| 42 | + max = Math.max(max, cnt); |
| 43 | + } |
| 44 | + |
| 45 | + static boolean isValidPath(int i, int j) { |
| 46 | + return 0 <= i && i < R && 0 <= j && j < C; |
| 47 | + } |
| 48 | +} |
0 commit comments