방문 길이

HeeSeong·2021년 3월 18일
0

프로그래머스

목록 보기
1/97
post-thumbnail

🔗 문제 링크

https://programmers.co.kr/learn/courses/30/lessons/49994


❔ 문제 설명


게임 캐릭터를 4가지 명령어를 통해 움직이려 합니다. 명령어는 다음과 같습니다.

  • U: 위쪽으로 한 칸 가기

  • D: 아래쪽으로 한 칸 가기

  • R: 오른쪽으로 한 칸 가기

  • L: 왼쪽으로 한 칸 가기


캐릭터는 좌표평면의 (0, 0) 위치에서 시작합니다. 좌표평면의 경계는 왼쪽 위(-5, 5), 왼쪽 아래(-5, -5), 오른쪽 위(5, 5), 오른쪽 아래(5, -5)로 이루어져 있습니다.



이때, 우리는 게임 캐릭터가 지나간 길 중 캐릭터가 처음 걸어본 길의 길이를 구하려고 합니다.

단, 좌표평면의 경계를 넘어가는 명령어는 무시합니다.

명령어가 매개변수 dirs로 주어질 때, 게임 캐릭터가 처음 걸어본 길의 길이를 구하여 return 하는 solution 함수를 완성해 주세요.


⚠️ 제한사항


  • dirs는 string형으로 주어지며, 'U', 'D', 'R', 'L' 이외에 문자는 주어지지 않습니다.

  • dirs의 길이는 500 이하의 자연수입니다.



💡 풀이 (언어 : Java & Python)


4차원 배열로 방문한 경로인지 체크한다. 주의할 점은 출발점과 도착점의 순서가 바뀐 경로도 방문한 것으로 체크해주어야 한다. 그리고 4차원 배열에서 저장할 때 음수 인덱스는 포함하지 못하므로, 11 크기의 4차원 배열의 +5씩 해준 인덱스 위치에 방문여부를 저장한다. 마지막으로 이동중 좌표평면의 범위를 벗어나지 않는지 체크하면 된다.

Java

import java.util.Arrays;

public class Solution {
    public int solution(String dirs) {
        // 방문했었는지 체크하는 배열 (앞뒤 지점의 순서바꾼 경우도 체크하기 위한 4차원 배열)
        boolean[][][][] check = new boolean[11][11][11][11];
        // 현재 위치, 정답 카운트
        int[] position = {0, 0};
        int count = 0;
        for (char d : dirs.toCharArray()) {
            switch (d) {
                case 'U':
                    if (position[1] < 5) {
                        // 해당 전후 경로가 방문한적 없는 경로라면 false, 카운트하고 true로 바꿔줌
                        if (!check[position[0]+5][position[1]+5][position[0]+5][position[1]+6]) {
                            count++;
                            check[position[0]+5][position[1]+5][position[0]+5][position[1]+6] = true;
                            check[position[0]+5][position[1]+6][position[0]+5][position[1]+5] = true;
                        }
                        // 범위를 넘지 않았다면 명령대로 현재 위치 옮겨줌
                        position[1]++;
                    }
                    break;
                case 'D':
                    if (position[1] > -5) {
                        if (!check[position[0]+5][position[1]+5][position[0]+5][position[1]+4]) {
                            count++;
                            check[position[0]+5][position[1]+5][position[0]+5][position[1]+4] = true;
                            check[position[0]+5][position[1]+4][position[0]+5][position[1]+5] = true;
                        }
                        position[1]--;
                    }
                    break;
                case 'L':
                    if (position[0] > -5) {
                        if (!check[position[0]+5][position[1]+5][position[0]+4][position[1]+5]) {
                            count++;
                            check[position[0]+5][position[1]+5][position[0]+4][position[1]+5] = true;
                            check[position[0]+4][position[1]+5][position[0]+5][position[1]+5] = true;
                        }
                        position[0]--;
                    }
                    break;
                case 'R':
                    if (position[0] < 5) {
                        if (!check[position[0]+5][position[1]+5][position[0]+6][position[1]+5]) {
                            count++;
                            check[position[0]+5][position[1]+5][position[0]+6][position[1]+5] = true;
                            check[position[0]+6][position[1]+5][position[0]+5][position[1]+5] = true;
                        }
                        position[0]++;
                    }
            }
        }
        return count;
    }
}

Python

def solution(dirs):
    # 시작점
    point = [0, 0]

    # 방향별 좌표 변화
    u = [1, 0]
    d = [-1, 0]
    r = [0, 1]
    l = [0, -1]

    # 거쳐간 길 체크 용도 리스트
    check = []
    # 새롭게 거쳐간 길 횟수
    count = 0

    for char in dirs:

        if char == "U":
            # 현재 지점에서 위로 이동했을 때 좌표 값
            after = [x+y for x,y in zip(point, u)]
            # 좌표 평면을 벗어난 경우 이동하지 않고 스킵
            if after[0] > 5:
                continue

            # 체크 리스트에 [x1, y1 (지금 좌표), x2, y2 (이동 후 좌표)] 형태로 넣기
            # 반대 순서로도 같은 길이므로 만들어서 넣어주기
            bef_aft = point + after
            bef_aft2 = after + point
            # 중복 길이든 아니든 일단 현재 좌표는 명령대로 이동
            point = after

            # 지금 길이 지나왔던 길이 아닌 경우에만
            if bef_aft not in check and bef_aft2 not in check:
                # 처음 지나가는 새 길을 체크 리스트에 등록
                check.append(bef_aft)
                check.append(bef_aft2)
                # 새로운 길 지나가므로 카운트 
                count += 1

        elif char == "D":
            # 현재 지점에서 아래로 이동했을 때 좌표 값
            after = [x+y for x,y in zip(point, d)]
            if after[0] < -5:
                continue
            
            bef_aft = point + after
            bef_aft2 = after + point
            point = after

            if bef_aft not in check and bef_aft2 not in check:
                check.append(bef_aft)
                check.append(bef_aft2)
                count += 1

        elif char == "R":
            # 현재 지점에서 오른쪽으로 이동했을 때 좌표 값
            after = [x+y for x,y in zip(point, r)]
            if after[1] > 5:
                continue
            
            bef_aft = point + after
            bef_aft2 = after + point
            point = after

            if bef_aft not in check and bef_aft2 not in check:
                check.append(bef_aft)
                check.append(bef_aft2)
                count += 1

        elif char == "L":
            # 현재 지점에서 왼쪽으로 이동했을 때 좌표 값
            after = [x+y for x,y in zip(point, l)]
            if after[1] < -5:
                continue
            
            bef_aft = point + after
            bef_aft2 = after + point
            point = after

            if bef_aft not in check and bef_aft2 not in check:
                check.append(bef_aft)
                check.append(bef_aft2)
                count += 1

    return count

배울만한 풀이

def solution(dirs):
    # 세트를 사용해서 중복인 경로는 들어가지 않게 함
    s = set()
    d = {'U': (0,1), 'D': (0, -1), 'R': (1, 0), 'L': (-1, 0)}
    x, y = 0, 0
    
    for i in dirs:
        nx, ny = x + d[i][0], y + d[i][1]
        
        if -5 <= nx <= 5 and -5 <= ny <= 5:
            s.add((x,y,nx,ny))
            s.add((nx,ny,x,y))
            x, y = nx, ny

    # 같은 경우 두가지 케이스 (전, 후) (후, 전)를 넣어주므로 나누기 2한 값
    return len(s)//2
profile
끊임없이 성장하고 싶은 개발자

0개의 댓글