1+ from _collections import deque
2+ import sys
3+ sys .setrecursionlimit (10 ** 6 )
4+ n , m = map (int , input ().split ())
5+
6+ dx = [- 1 , 1 , 0 , 0 ]
7+ dy = [0 , 0 , - 1 , 1 ]
8+
9+ arr = [list (map (str , input ())) for _ in range (n )]
10+ dp = [[0 ] * m for _ in range (n )]
11+ visited = [[0 ] * m for _ in range (n )] #dp 배열추가
12+ # q = deque()
13+ # q.append((0, 0, 1))# x, y 좌표와 움직인 횟수
14+ result = 0 # 가장 큰 값을 저장해줄 변수
15+
16+ def bfs (x , y , count ):
17+ global result
18+ result = max (result , count )
19+
20+ for i in range (4 ):
21+ nx = x + dx [i ] * int (arr [x ][y ])
22+ ny = y + dy [i ] * int (arr [x ][y ])
23+
24+ if 0 <= nx < n and 0 <= ny < m and arr [nx ][ny ] != 'H' and dp [nx ][ny ] < count + 1 : #적은 이동횟수는 무시하는 조건 추가
25+ if visited [nx ][ny ]:
26+ print (- 1 )
27+ exit ()
28+ else :
29+ dp [nx ][ny ] = count + 1
30+ visited [nx ][ny ] = 1
31+ bfs (nx , ny , count + 1 )
32+ visited [nx ][ny ] = 0
33+
34+ bfs (0 , 0 , 0 )
35+ print (result + 1 )
36+
37+ # while q:
38+ # x, y, count = q.popleft()
39+ #
40+ # if count > n*m: #무한 반복될때 종료조건
41+ # print(-1)
42+ # quit()
43+ # for i in range(4):
44+ # nx = x + dx[i] * int(arr[x][y])
45+ # ny = y + dy[i] * int(arr[x][y])
46+ #
47+ # if 0 <= nx < n and 0 <= ny < m and arr[nx][ny] != 'H' and visited[nx][ny] < count: #적은 이동횟수는 무시하는 조건 추가
48+ # q.append((nx, ny, count+1))
49+ # visited[nx][ny] = count
50+ #
51+ #
52+ # for i in range(n):
53+ # for j in range(m):
54+ # result = max(result, visited[i][j])
55+ #
56+ # if result < n*m:
57+ # print(result + 1)
58+ # else:
59+ # print(-1)
60+
61+
62+ # bfs 함수 따로 뽑아서 하는거랑 메인에서 q 구현해서 하는거랑 대체 무슨 차이?
63+ # 밑에 1크게 시작하는거랑 무슨차이?
64+ '''
65+ def bfs(x, y, count):
66+ global result
67+ result = max(result, count)
68+
69+ for i in range(4):
70+ nx = x + dx[i] * int(arr[x][y])
71+ ny = y + dy[i] * int(arr[x][y])
72+
73+ if 0 <= nx < n and 0 <= ny < m and arr[nx][ny] != 'H' and dp[nx][ny] < count: #적은 이동횟수는 무시하는 조건 추가
74+ if visited[nx][ny]:
75+ print(-1)
76+ exit()
77+ else:
78+ dp[nx][ny] = count +1
79+ visited[nx][ny] = 1
80+ bfs(nx, ny, count+1)
81+ visited[nx][ny] = 0
82+
83+ bfs(0, 0, 1)
84+ print(result)
85+ '''
0 commit comments