8911 거북이
단순한 구현문제다.
방향을 회전하며 1칸씩 앞뒤로 움직일 수 있는 거북이가 있다. 움직인 경로에 대해 가장 작은 직사각형의 넓이를 구하는 문제다.
넓이는 가로*세로이므로,
가로 = 움직인 경로중 가장 왼쪽(minX) + 움직인 경로중 가장 오른쪽(maxX)
세로 = 움직인 경로중 가장 위쪽(minY) + 움직인 경로중 가장 아래쪽(maxY)
minX, maxX, minY, maxY를 움직일 때마다 업데이트해주면 된다.
int f_set[4][2] = {
{-1, 0}, {0, 1},
{1, 0}, {0, -1}
};
int b_set[4][2] = {
{1, 0}, {0, -1},
{-1, 0}, {0, 1}
};
int minX, maxX, minY, maxY;
void updateResultLocation(int x, int y) {
minX = min(x, minX);
minY = min(y, minY);
maxX = max(x, maxX);
maxY = max(y, maxY);
};
int main(int argc, const char * argv[]) {
int num;
cin>>num;
cin.ignore();
for(int k = 0; k<num; k++) {
string moveArea;
getline(cin, moveArea);
int length = (int) moveArea.length();
minX = 0; maxX = 0; minY = 0; maxY = 0;
int c_y = 0;
int c_x = 0;
int c_dir = 0;
for(int i = 0; i<length; i+=1) {
if(moveArea[i] == 'F') {
c_y += f_set[c_dir][0];
c_x += f_set[c_dir][1];
updateResultLocation(c_x, c_y);
} else if (moveArea[i] == 'B') {
c_y += b_set[c_dir][0];
c_x += b_set[c_dir][1];
updateResultLocation(c_x, c_y);
} else if (moveArea[i] == 'L') {
c_dir -= 1;
if(c_dir < 0) {
c_dir = 3;
}
} else if (moveArea[i] == 'R') {
c_dir += 1;
if(c_dir > 3) {
c_dir = 0;
}
}
}
// cout<<"x: "<<c_x<<endl;
// cout<<"y: "<<c_y<<endl<<endl;
//
// cout<<"maxX: "<<maxX<<endl;
// cout<<"maxY: "<<maxY<<endl<<endl;
//
// cout<<"minX: "<<minX<<endl;
// cout<<"minY: "<<minY<<endl<<endl;
int line_x = abs(maxX) + abs(minX);
int line_y = abs(maxY) + abs(minY);
int result = line_x * line_y;
// cout<<"result: "<<result<<endl;
cout<<result<<endl;
}
return 0;
}
Last updated
Was this helpful?