Photo by Pietro Mattia on Unsplash
row, col = map(int, input().split())
cur_y,cur_x, pos = (map(int, input().split()))
visited =[[0] * col for _ in range(row)]
map_ = []
for _ in range(row):
map_.append(list(map(int, input().split())))
visited[cur_y][cur_x] = 1
cnt = 1
turn_time = 0
# 북 동 남 서
dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]
while True:
# 포지션을 왼쪽으로 돌림
pos = 3 if pos-1 == -1 else pos -1
ny = cur_y + dy[pos]
nx = cur_x + dx[pos]
if visited[ny][nx]==0 and map_[ny][nx] == 0:
visited[ny][nx] = 1
cur_y = ny
cur_x = nx
cnt += 1
turn_time = 0
continue
else:
# 왼쪽으로 돌았을 때 청소가 불가능하다면 다음바퀴를 돌림
turn_time += 1
if turn_time == 4:
# 네번째 바퀴를 마치고 나서 뒤로 이동
ny = cur_y - dy[pos]
nx = cur_x - dx[pos]
# 청소가 가능하면 이동
if map_[ny][nx] == 0:
cur_x = nx
cur_y = ny
# 아니라면 종료
else:
break
turn_time = 0
print(cnt)