[프로그래머스] 방문 길이

HL·2021년 3월 23일
0

프로그래머스

목록 보기
36/44

문제 링크

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

문제 설명

  • 이동 방향 리스트가 주어진다
  • (0,0)에서 시작해 처음 지나는 길의 길이를 리턴

풀이

  • set 또는 HashSet에 저장
    • 자바에서는 클래스를 만들면 equals, hashCode 메소드를 오버라이드를 해야한다고 해서 그냥 String으로 변환했다
  • 파이썬 최고

코드

Python

def solution(dirs):
    count = 0
    visited = set()
    cy, cx = 0, 0
    for i in range(len(dirs)):
        ny, nx = get_next((cy, cx), dirs[i])
        if -5 <= ny <= 5 and -5 <= nx <= 5:
            if (cy, cx, ny, nx) not in visited and (ny, nx, cy, cx) not in visited:
                visited.add((cy, cx, ny, nx))
                count += 1
            cy, cx = ny, nx
    return count


def get_next(curr, d):
    cy, cx = curr
    if d == 'U':
        return cy+1, cx
    elif d == 'D':
        return cy-1, cx
    elif d == 'L':
        return cy, cx-1
    elif d == 'R':
        return cy, cx+1

Java

import java.util.HashSet;

class Solution {

    HashSet<String> visited = new HashSet<>();
    int count = 0;
    int cy = 0, cx = 0;

    public int solution(String dirs) {
        for(int i=0; i<dirs.length(); i++){
            int[] next = get_next(cy, cx, dirs.charAt(i));
            int ny = next[0], nx = next[1];
            if(-5<=ny && ny<=5 && -5<=nx && nx<=5){
                if(!visited.contains(""+cy+cx+ny+nx) && !visited.contains(""+ny+nx+cy+cx)){
                    visited.add(""+cy+cx+ny+nx);
                    count += 1;
                }
                cy = ny; cx = nx;
            }
        }
        return count;
    }

    int[] get_next(int cy, int cx, char d){
        int[] next = {cy, cx};
        if(d == 'U')
            next[0] += 1;
        else if(d == 'D')
            next[0] -= 1;
        else if(d == 'L')
            next[1] -= 1;
        else
            next[1] += 1; 
        return next;
    }
}
profile
Swift, iOS 앱 개발을 공부하고 있습니다

0개의 댓글