코테 대비 python/백준
14503 로봇 청소기
ylab
2023. 4. 11. 00:48
https://www.acmicpc.net/problem/14503
14503번: 로봇 청소기
첫째 줄에 방의 크기 $N$과 $M$이 입력된다. $(3 \le N, M \le 50)$ 둘째 줄에 처음에 로봇 청소기가 있는 칸의 좌표 $(r, c)$와 처음에 로봇 청소기가 바라보는 방향 $d$가 입력된다. $d$가 $0$인 경우 북쪽
www.acmicpc.net
n,m = map(int,input().split())
r,c,d = map(int,input().split())
graph = [list(map(int,input().split())) for _ in range(n)]
visited = [[0]*m for _ in range(n)]
#처음 빈칸은 전부 청소되지 않은 상태이다.
#순서대로 구현하자!!
#청소하는칸 카운트
cnt=0
#방향 조건에 맞게 상우하좌 1씩 빼면 반시계 90도 0일때는 3으로
dx=[-1,0,1,0]
dy=[0,1,0,-1]
while 1:
flag = 0
if visited[r][c]==0:
visited[r][c]=1
cnt+=1
#현재 칸의 주변 4칸 중 청소되지 않은 빈 칸이 없는 경우
for i in range(4):
nx=r+dx[i]
ny=c+dy[i]
#범위 안에 있으며, 방문하지 않았고, 벽이 아니라 빈칸이면
if 0<=nx<n and 0<=ny<m and visited[nx][ny]==0 and graph[nx][ny]==0:
#청소안한 빈칸 있는거
flag=1
#빈칸없어 뒤로 후진해야됨
if flag==0:
if d==0:
nx = r + dx[2]
ny = c + dy[2]
if 0 <= nx < n and 0 <= ny < m and visited[nx][ny] == 0 and graph[nx][ny] == 0:
cnt+=1
visited[nx][ny] = 1
r,c=nx,ny
elif 0 <= nx < n and 0 <= ny < m and visited[nx][ny] == 1 and graph[nx][ny] == 0:
r, c = nx, ny
elif 0 <= nx < n and 0 <= ny < m and graph[nx][ny] == 1:
print(cnt)
break
elif d==1:
nx = r + dx[3]
ny = c + dy[3]
if 0 <= nx < n and 0 <= ny < m and visited[nx][ny] == 0 and graph[nx][ny] == 0:
cnt+=1
visited[nx][ny] = 1
r, c = nx, ny
elif 0 <= nx < n and 0 <= ny < m and visited[nx][ny] == 1 and graph[nx][ny] == 0:
r, c = nx, ny
elif 0 <= nx < n and 0 <= ny < m and graph[nx][ny] == 1:
print(cnt)
break
elif d==2:
nx = r + dx[0]
ny = c + dy[0]
if 0 <= nx < n and 0 <= ny < m and visited[nx][ny] == 0 and graph[nx][ny] == 0:
cnt+=1
visited[nx][ny] = 1
r, c = nx, ny
elif 0 <= nx < n and 0 <= ny < m and visited[nx][ny] == 1 and graph[nx][ny] == 0:
r, c = nx, ny
elif 0 <= nx < n and 0 <= ny < m and graph[nx][ny] == 1:
print(cnt)
break
elif d==3:
nx = r + dx[1]
ny = c + dy[1]
if 0 <= nx < n and 0 <= ny < m and visited[nx][ny] == 0 and graph[nx][ny] == 0:
cnt+=1
r, c = nx, ny
elif 0 <= nx < n and 0 <= ny < m and visited[nx][ny] == 1 and graph[nx][ny] == 0:
r, c = nx, ny
elif 0 <= nx < n and 0 <= ny < m and graph[nx][ny] == 1:
print(cnt)
break
elif flag==1:
if d==0:
#90도로 방향돌리기
d=3
else:
#90도로 방향돌리기
d-=1
nx = r + dx[d]
ny = c + dy[d]
if 0 <= nx < n and 0 <= ny < m and visited[nx][ny] == 0 and graph[nx][ny] == 0:
#방문표시
visited[nx][ny]=1
r, c = nx, ny
cnt+=1
리펙토링이 필요하긴하다..
실전에서는?? 함수화하는게 관리가 편하려나