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
| n,m = list(map(int, input().split()))
board = []
for _ in range(n):
board.append(list(input()))
directions = [
[0,1],[0,-1],[1,0],[-1,0]
]
check = [0]* 26
max_value = 0
check[ord(board[0][0]) - 65] = 1
def backtrack(x,y,count):
global n,m,board,max_value
for i in range(4):
nx = x + directions[i][0]
ny = y + directions[i][1]
if nx < 0 or ny < 0 or nx >= n or ny >= m:
continue
if check[ord(board[nx][ny]) - 65] == 1:
continue
check[ord(board[nx][ny]) - 65] = 1
backtrack(nx,ny,count + 1)
check[ord(board[nx][ny]) - 65] = 0
max_value = max(max_value, count)
backtrack(0,0,1)
print(max_value)
|