코딩테스트/프로그래머스
[프로그래머스] 공원 산책
쪼르뚜
2024. 7. 2. 14:13
728x90
반응형
🔗 문제 링크
https://school.programmers.co.kr/learn/courses/30/lessons/172928
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
👩💻 코드
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<string> park, vector<string> routes) {
int H = park.size();
int W = park[0].size();
pair<int, int> position;
for (int i = 0; i < H; ++i) {
for (int j = 0; j < W; ++j) {
if (park[i][j] == 'S') {
position = {i, j};
break;
}
}
}
for (const string& route : routes) {
char direction = route[0];
int distance = route[2] - '0';
int dx = 0, dy = 0;
if (direction == 'N') dx = -1;
else if (direction == 'S') dx = 1;
else if (direction == 'W') dy = -1;
else if (direction == 'E') dy = 1;
bool can_move = true;
for (int step = 1; step <= distance; ++step) {
int new_x = position.first + dx * step;
int new_y = position.second + dy * step;
if (new_x < 0 || new_x >= H || new_y < 0 || new_y >= W || park[new_x][new_y] == 'X') {
can_move = false;
break;
}
}
if (can_move) {
position.first += dx * distance;
position.second += dy * distance;
}
}
return {position.first, position.second};
}
📝 풀이
처음 for문에서 'S'문자를 찾아 시작 위치 좌표를 설정합니다.
그 후 수행할 수 있는 명령인지 확인하는 for문을 작성합니다.
방향에 따라 x값이 감소하거나 증가하는지 y값이 감소하거나 증가하는지 지정합니다.
명령을 수행하고자 하는 방향까지 한 칸씩 움직이면서 조건을 확인합니다.
공원을 벗어나거나 장애물을 만나면 움직일 수 없고 다음 명령을 수행합니다.
움직일 수 있는 상태라면 위치 좌표를 업데이트 해줍니다.
최종적으로 설정된 위치 좌표가 명령을 모두 수행 한 후 위치 좌표가 됩니다.
728x90
반응형