import sys
input=sys.stdin.readline
L_I=lambda:list(map(int,input().split()))
I_S=lambda:map(int,input().split())
V_L_I=lambda:[ L_I() for _ in range(N) ]
def BFS(x,y,d):
# d 0 : 북 , 1 : 동 , 2: 남 , 3 : 서
total = 0
if graph[x][y]==0: total+=1
visit=[ [0]*M for _ in range(N) ]
visit[x][y]=1
while True:
if d==0: # 북
if y-1>=0 and graph[x][y-1]==0 and not visit[x][y-1]: #서
total+=1
visit[x][y-1]=visit[x][y]+1
y-=1
d=3
elif x+1<N and graph[x+1][y]==0 and not visit[x+1][y]: #남
total+=1
visit[x+1][y]=visit[x][y]+1
x+=1
d=2
elif y+1<M and graph[x][y+1]==0 and not visit[x][y+1]: # 동
total+=1
visit[x][y+1]=visit[x][y]+1
y+=1
d=1
elif x-1>=0 and graph[x-1][y]==0 and not visit[x-1][y]: #북
total+=1
visit[x-1][y]=visit[x][y]+1
x-=1
else:
if x+1<N and graph[x+1][y]==0:
visit[x+1][y]=visit[x][y]
x+=1
else:
return total
elif d==1: #동
if x-1>=0 and graph[x-1][y]==0 and not visit[x-1][y]: # 북
total+=1
visit[x-1][y]=visit[x][y]+1
x-=1
d=0
elif y-1>=0 and graph[x][y-1]==0 and not visit[x][y-1]: #서
total+=1
visit[x][y-1]=visit[x][y]+1
y-=1
d=3
elif x+1<N and graph[x+1][y]==0 and not visit[x+1][y]:#남
total+=1
visit[x+1][y]=visit[x][y]+1
x+=1
d=2
elif y+1<M and graph[x][y+1]==0 and not visit[x][y+1]: #동
total+=1
visit[x][y+1]=visit[x][y]+1
y+=1
else:
if y-1>=0 and graph[x][y-1]==0:
visit[x][y]=visit[x][y-1]
y-=1
else:
return total
elif d==2: #남
if y+1<M and graph[x][y+1]==0 and not visit[x][y+1]: #동
total+=1
visit[x][y+1]=visit[x][y]+1
y+=1
d=1
elif x-1>=0 and graph[x-1][y]==0 and not visit[x-1][y]:# 북
total+=1
visit[x-1][y]=visit[x][y]+1
x-=1
d=0
elif y-1>=0 and graph[x][y-1]==0 and not visit[x][y-1]: # 서
total+=1
visit[x][y-1]=visit[x][y]+1
y-=1
d=3
elif x+1<N and graph[x+1][y]==0 and not visit[x+1][y]: #남
total+=1
visit[x+1][y]=visit[x][y]+1
x+=1
else:
if x-1>=0 and graph[x-1][y]==0:
visit[x-1][y]=visit[x][y]
x-=1
else:
return total
elif d==3: #서
if x+1<N and graph[x+1][y]==0 and not visit[x+1][y]: # 남
total+=1
visit[x+1][y]=visit[x][y]+1
x+=1
d=2
elif y+1<M and graph[x][y+1]==0 and not visit[x][y+1]: #동
total+=1
visit[x][y+1]=visit[x][y]+1
y+=1
d=1
elif x-1>=0 and graph[x-1][y]==0 and not visit[x-1][y]: # 북
total+=1
visit[x-1][y]=visit[x][y]+1
x-=1
d=0
elif y-1>=0 and graph[x][y-1]==0 and not visit[x][y-1]:#서
total+=1
visit[x][y-1]=visit[x][y]+1
y-=1
else:
if y+1<M and graph[x][y+1]==0:
visit[x][y+1]=visit[x][y]
y+=1
else:
return total
N,M=L_I()
x,y,d=L_I()
graph=V_L_I()
print( BFS(x,y,d) )
✅ 어떻게 접근할 것인가?
삼성문제집에 있는 구현문제입니다.
문제에서 주어지는대로 그대로 구현하면되는데 주의해야할 점은
현재 칸의 주변 4칸 중 청소되지 않은 빈 칸이 있는 경우 회전을 먼저하고 이동을 해야합니다.
또한 visit 방문처리 배열을 통해 빈칸 , 청소한칸 을 구분했습니다. 기본적으로 빈칸은 전부다 청소가 되지않은 상태이지만 빈칸을 방문하면 청소한칸으로 변합니다. 그리고 빈칸은 청소한칸일지라도 이동이 가능합니다.
d 라는 변수를 통해 상하좌우 방향을 저장했고 만약 청소하지않은 칸으로 이동할시 기존의 좌표 visit[x][y] 에 +1 값을 이동할 칸에 넣어주었습니다.
만약 빈칸이지만 이미 청소한칸을 방문할 경우 다음으로 이동할 칸에 visit[x][y] 좌표값을 그대로 대입했습니다.
또한 처음 위치도 방문체크를 하고 total 값도 1로 시작해야합니다.