본문 바로가기

PS/프로그래머스

[프로그래머스 LV 2] 방문길이 (파이썬/python)

728x90

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

 

코딩테스트 연습 - 방문 길이

 

programmers.co.kr

 

ㅋㅋㅋ 두가지 풀이법을 올릴건데

첫번째 풀이는 내가 고안한 풀이

삼차원배열로 방문한 길인지 아닌지를 체크해줬다

 

코드길이를 보면 알겠지만 무식하고 단순한 방법.

맞긴 했지만 이건 아닌것 같아서 푼 후에 다른 풀이를 찾아보았다

 

파이썬 set 으로 푼 풀이를 보았다.

순서가 없고 중복이 없는 집합이다.

 

3차원배열 선언 파이썬으로는 처음해봤고

set도 처음써봤다 

 

 

내가 푼 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def solution(dirs):
    # 10*10 이차원 배열을 좌표 평면으로 구성
    # [6][6] == 원점
    # 위 = 0 / 오른 = 1 / 아래 = 2 / 왼 = 3
    location = [[[0 for k in range(4)] for j in range(11)] for i in range(11)]
    hear = [55]
    first_root = 0
 
    for d in dirs:
        if d == 'U':
            if hear[0- 1 >= 0:
                # 가본적 없는 길이라면
                if location[hear[0]][hear[1]][0== 0:
                    location[hear[0]][hear[1]][0= 1
                    hear[0-= 1
                    location[hear[0]][hear[1]][2= 1
                    first_root += 1
                else:
                    # 가본적 있는 길이라면
                    hear[0-= 1
        if d == 'D':
            if hear[0+ 1 <= 10:
                if location[hear[0]][hear[1]][2== 0:
                    location[hear[0]][hear[1]][2= 1
                    hear[0+= 1
                    location[hear[0]][hear[1]][0= 1
                    first_root += 1
                else:
                    hear[0+= 1
 
        if d == 'R':
            if hear[1+ 1 <= 10:
                if location[hear[0]][hear[1]][1== 0:
                    location[hear[0]][hear[1]][1= 1
                    hear[1+= 1
                    location[hear[0]][hear[1]][3= 1
                    first_root += 1
                else:
                    hear[1+= 1
        if d == 'L':
            if hear[1- 1 >= 0:
                if location[hear[0]][hear[1]][3== 0:
                    location[hear[0]][hear[1]][3= 1
                    hear[1-= 1
                    location[hear[0]][hear[1]][1= 1
                    first_root += 1
                else:
                    hear[1-= 1
 
    return first_root
cs

 

 

 

남의 코드 참고한 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def solution(dirs):
    answer = 0
 
    # 위 오른 밑 왼
    dx = [010-1]
    dy = [10-10]
    dic = {"U"0"R"1'D'2"L"3}
 
    x, y = 00
 
    visit = set()
 
    for d in dirs:
        idx = dic[d]
        nx, ny = x + dx[dic[d]], y + dy[dic[d]]
 
        if nx < -5 or nx > 5 or ny > 5 or ny < -5:
            continue
 
        if (x, y, nx, ny) not in visit:
            visit.add((x, y, nx, ny))
            visit.add((nx, ny, x, y))
            answer += 1
        x, y = nx, ny
 
    return answer
cs
728x90