프로그래머스 - 방문 길이

well-life-gm·2021년 11월 5일
0

프로그래머스

목록 보기
26/125

프로그래머스 - 방문 길이

사진1
사진2
위와 같이 문자열이 주어지고, 그 방향대로 맵을 이동할 때, 실제로 이동한 거리가 얼마인지 구하는 문제이다.
단 맵 밖으로 나가도록 유도하는 문자는 그냥 넘긴다. 위와 같은 경우는 7번과 8번이 맵 밖으로 나가도록 하는 문자이기 때문에 생략하고 9번을 수행한다.

제출했을 때 8번부터 통과가 안되서 뭔가했는데, 대충짠게 패착이었다; (UDU의 경우 답이 1로 나오는지 체크해자...)

일단 방식은 row_visit 맵과 col_visit 맵을 관리해서 direction이 상, 하로 움직일 땐 col_visit 맵을 체크하도록하고, 좌, 우로 움직일 땐 row_visit 맵을 체크하도록 했다.

예를 들어,
(0, 0)에서 (0, 1)로 움직일 땐 col_visit[0][0]을 확인하고, (0, 0)에서 (1, 0)로 움직일 땐 row_visit[0][0]을 확인한다. (코드에선 (0, 0)을 (5, 5)로 치환해서 사용한다)

코드는 아래와 같다.

#include <string>
#include <cstdio>
using namespace std;

typedef struct __pos {
    int row;
    int col;
} pos;
int rowDir[4] = { -1, 0, 1, 0 };
int colDir[4] = { 0, 1, 0, -1 };
#define MAX_LIMIT 5
#define MIN_LIMIT -5
const inline int getDirIndex(char d)
{
    switch(d) {
        case 'U':
            return 0;
        case 'R':
            return 1;
        case 'D':
            return 2;
        case 'L':
            return 3;
    }
}
const inline bool is_safe(pos p)
{
    if(p.row > MAX_LIMIT || p.col > MAX_LIMIT || p.row < MIN_LIMIT || p.col < MIN_LIMIT)
        return false;
    return true;
}
int row_visit[12][12];
int col_visit[12][12];
int solution(string dirs) {
    int answer = 0;
    pos cpos = { 0, 0 };
    pos npos, idx;
    for(int i=0;i<dirs.size();i++) {
        int dir = getDirIndex(dirs[i]);
        npos.row = cpos.row + rowDir[dir];
        npos.col = cpos.col + colDir[dir];
        if(!is_safe(npos))
            continue;
        if(dir == 1 || dir == 3) {
            idx = npos.col < cpos.col ? npos : cpos;
            if(row_visit[idx.row + MAX_LIMIT][idx.col + MAX_LIMIT] == 0) {
                row_visit[idx.row + MAX_LIMIT][idx.col + MAX_LIMIT] = 1;
                answer++;
            }
        } else {
            idx = npos.row < cpos.row ? npos : cpos;
            if(col_visit[idx.row + MAX_LIMIT][idx.col + MAX_LIMIT] == 0) {
                col_visit[idx.row + MAX_LIMIT][idx.col + MAX_LIMIT] = 1;
                answer++;
            }
        }
        cpos = npos;
    }
    return answer;
}

결과

profile
내가 보려고 만든 블로그

0개의 댓글