로봇 청소기가 주어졌을 때, 청소하는 영역의 개수를 구하기.
입력 | 출력 |
---|---|
3 3 1 1 0 1 1 1 1 0 1 1 1 1 | 1 |
11 10 7 4 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 0 1 1 0 0 0 0 1 1 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 0 1 1 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 | 57 |
:
시뮬레이션 문제는 문제에서 나와있는대로 충실히 구현하면 된다. 특히 이 문제는 한 번에 움직일 수 있는 한 방향이 정해져 있으므로 특별한 알고리즘도 필요하지 않다.
n, m = list(map(int, input().split())) # n*m
r, c, d = list(map(int, input().split()))
# d가 0:북, 1:동, 2:남, 3:서
maps = [list(map(int, input().split())) for _ in range(n)] # 빈칸0, 벽1
# 방향 바꾸기 함수
def change_direction(d):
if d==0: return 3
elif d==1: return 0
elif d==2: return 1
elif d==3: return 2
# (있는 자리)청소하기 함수
def clean(x, y, d):
maps[x][y] = -1
cnt = 1
# 북동남서
dx = [-1,0,1,0]
dy = [0,1,0,-1]
while True:
flag = 0
# 한 자리에서 네번 돌 수 있음.
for _ in range(4):
nd = change_direction(d) #방향바꾸기
nx = x + dx[nd]
ny = y + dy[nd]
d = nd
if 0<=nx<n and 0<=ny<m: #map안에 있어야함
if maps[nx][ny] == 0:
maps[nx][ny] = -1 #청소
x, y = nx, ny #이동
flag += 1 #청소 여부
cnt += 1 #청
break
if flag == 0 : #본인 제외 청소 하나도 못함 or 모두 청소
nx = x - dx[d] #후진
ny = y - dy[d]
if 0<=nx<n and 0<=ny<m:
if maps[nx][ny] != 1: #map안에 있으면서 벽만 아니면 후진.
x, y = nx, ny
else:
return cnt
else:
return cnt
print(clean(r, c, d))