목표 : 로봇 청소기를 이동시킬 때 청소할 수 있는 영역의 수를 구하자.
조건 : 1 <= N,M<= 50, 현재 위치를 청소하고 왼쪽 방향으로 돌면서 청소할 영역을 탐색하고 해당 영역이 없으면 후진한다. 이때 후진할 영역이 벽이면 청소를 종료한다.
벽과 청소한 영역을 잘 구분하자. 후진할 때는 방향은 바뀌지 않고 청소한 영역이라도 이동할 수 있다.
#include <stdio.h>
using namespace std;
int N, M, nx, ny, dir, dx[] = {-1,0,1,0}, dy[] = {0,1,0,-1};
int input[51][51];
int main() {
scanf("%d%d",&N,&M);
scanf("%d%d%d",&nx,&ny,&dir);
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
scanf("%d",&input[i][j]);
}
}
int ans = 0;
while(1){
if (!input[nx][ny]){
ans++;
}
input[nx][ny] = 2; // 현재 영역 청소 완료
bool chk = false;
int i, tx, ty;
for (i = 0; i < 4; i++){
dir -= 1;
if (dir < 0){ dir = 3; }
tx = nx + dx[dir], ty = ny + dy[dir];
if (input[tx][ty]){
continue;
}
chk = true;
nx = tx, ny = ty;
break;
}
if (!chk){ // 후진할 때는 방향은 바귀지 않음
int t;
if (dir == 0){ t = 2; }
else if (dir == 1){ t = 3; }
else if (dir == 2){ t = 0; }
else { t = 1; }
tx = nx + dx[t], ty = ny + dy[t];
if (input[tx][ty] == 1){
break;
}
else{
nx = tx, ny = ty;
}
}
}
printf("%d\n",ans);
return 0;
}