본문 바로가기

알고리즘 문제풀이/백준

백준(boj) 14503_로봇청소기 (파이썬, c++)

https://www.acmicpc.net/problem/14503

풀이


주어진 문제대로 잘 따라 만들면 되는 시뮬레이션 문제이다.

4방향을 탐색하면서 청소할 곳이 있으면 그곳에 가서 청소한다. 청소한 곳은 2로 표시해둔다. 4방향 모두 청소할 곳이 없다면, 뒤로 이동한다. 만약 뒤가 벽이면 끝내고, 벽이 아니라면 그곳으로 가서 다시 4방향을 탐색한다.

python3

from sys import*
from collections import*
input = stdin.readline
n,m=map(int,input().split())
x, y, d = map(int,input().split())
a=[list(map(int,input().split()))for _ in range(n)]
dd=[(-1,0),(0,1),(1,0),(0,-1)]  #URDL
res=1
a[x][y]=2
while 1:
   f=False
   for i in range(4):
       nd=(d+3-i)%4
       dx, dy = dd[nd]
       nx, ny = x+dx, y+dy
       if a[nx][ny]!=0:continue
       a[nx][ny]=2
       f=True
       res+=1
       d=nd
       break
   if not f:
       nx, ny = x-dx, y-dy
       if a[nx][ny]==1:break        
   x, y = nx, ny
print(res)

C++

#include<cstdio>
using namespace std;

int n, m, x, y, d, a[50][50];
int dd[][2]= {{-1,0}, {0,1}, {1,0}, {0,-1}};
int main(){
   scanf("%d %d", &n, &m);
   scanf("%d %d %d", &x, &y, &d);
   for(int i=0; i<n; i++){
       for(int j=0; j<m; j++){
           scanf("%d", &a[i][j]);
      }
  }
   int res=1;
   a[x][y]=2;
   while(1){
       int dx, dy, nx, ny, nd;
       bool f = false;
       for(int i=0; i<4; i++){
           nd = (d+3-i)%4;
           dx = dd[nd][0], dy = dd[nd][1];
           nx = x+dx, ny = y+dy;
           if(a[nx][ny]!=0) continue;
           a[nx][ny]=2;
           f=true;
           res++;
           d=nd;
           break;
      }
       if(!f){
           nx = x-dx, ny = y-dy;
           if(a[nx][ny]==1) break;
      }
       x = nx, y = ny;
  }
   printf("%d", res);
   return 0;
}

고찰


.