프로그래머스/1레벨

[프로그래머스/C++] 공원 산책

Koalitsiya 2023. 7. 5. 11:41
 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

 

1. 시작점을 찾는다.

2. routes를 순회하며 각 방향으로 지정된 횟수만큼 {curX, curY}를 이동하며 범위를 벗어나는지, 도중에 X가 있는지 체크한다.

3. 순회가 끝난 후 { nowCoordinate.first, nowCoordinate.second }를 리턴한다.

#include <string>
#include <vector>
#include <map>

using namespace std;

map<char, int> m = {{'E', 0}, {'W', 1}, {'S', 2}, {'N', 3}};
int dirX[4] = {0, 0, 1, -1};
int dirY[4] = {1, -1, 0, 0};

vector<int> solution(vector<string> park, vector<string> routes) {
    pair<int, int> nowCoordinate;
    
    int height = park.size();
    int width = park[0].size();
    
    for(int i = 0; i < height; i++)
        for(int j = 0; j < width; j++)
            if(park[i][j] == 'S') {
                nowCoordinate = {i, j};
                break;
            }
    
    for(int i = 0; i < routes.size(); i++) {
        int dir = m[routes[i][0]];
        int dis = routes[i][2] - 48;
        
        int curX = nowCoordinate.first;
        int curY = nowCoordinate.second;
        
        for(;dis > 0; dis--) {
            curX += dirX[dir];
            curY += dirY[dir];
            
            if(curX >= height || curX < 0 || curY >= width || curY < 0 || park[curX][curY] == 'X') break;
        }
        
        if(dis <= 0) nowCoordinate = {curX, curY};
    }
    
    return { nowCoordinate.first, nowCoordinate.second };
}