(Python)백준-로봇청소기

DongDong·2023년 10월 29일
0

알고리즘 문제풀이

목록 보기
17/20
post-thumbnail

로봇청소기

문제

입력

풀이

처음에 문제 이해를 잘못해서 풀이를 이상하게 했었다.
(3.현재 칸 주변 4칸 중 청소되지 않은 빈칸이 있는 경우
반시계 방향으로 90도 회전한다. 바라보는 방향 기준 앞칸이 청소되지 않은 빈 칸인 경우 한칸 전진한다.)
주변 4칸은 상하좌우 칸들을 의미하는 것이고 주변 4칸 중 청소되지 않은 빈칸이 있는 경우 반시계 방향으로 90도 회전한다. 만약 회전했을 때 바라보는 방향 기준 앞칸이 청소가 되어 있는 칸 또는 벽일 경우 청소되지 않은 빈칸이 나올 때까지 반시계 방향으로 90도 회전시켜줘야한다.
반시계 90도를 잘 보고 방향도 잘 설정해 줄 것 !!
문제를 잘 읽고 잘 이해하면 BFS로 어렵지 않게 풀 수 있는 것 같다.

import sys
from collections import deque
input=sys.stdin.readline

n,m=map(int,input().split())

r,c,dic=map(int,input().split())

graph=[]
for i in range(n):
    graph.append(list(map(int,input().split())))


def robot(r,c,dic,graph):
    # 북, 동, 남, 서
    dx=[-1,0,1,0]
    dy=[0,1,0,-1]   

    q=deque()
    q.append((dic,r,c)) # 좌표와 바라보는 방향
    result=0 #청소하는 칸 수 
    while q:#q가 빌때까지
        now,x,y=q.popleft()
        if graph[x][y]==0:
            result+=1
            graph[x][y]=2
        count=0
        for i in range(4):
            #반시계 방향 90도 회전
            nd=(now+3)%4
            nx=x+dx[nd]
            ny=y+dy[nd]
            if graph[nx][ny]==0:
                count+=1
                q.append((nd,nx,ny))
                break
            else:
                now=nd

        # 현재 칸 주변 4칸 중 청소되지 않은 빈칸 없을 때
        if count==0:
            if now==0:
                nx=x+1
                ny=y
                if graph[nx][ny]==1:
                    break
                else:
                    q.append((now,nx,ny))
            elif now==1:
                nx=x
                ny=y-1
                if graph[nx][ny]==1:
                    break
                else:
                    q.append((now,nx,ny))
            elif now==2:
                nx=x-1
                ny=y
                if graph[nx][ny]==1:
                    break
                else:
                    q.append((now,nx,ny))
            elif now==3:
                nx=x
                ny=y+1
                if graph[nx][ny]==1:
                    break
                else:
                    q.append((now,nx,ny))
    return result
answer=robot(r,c,dic,graph)
print(answer)

0개의 댓글