programmers | Lv2. ๋ฐฉ๋ฌธ ๊ธธ์ด [Python]

yeonkยท2022๋…„ 2์›” 26์ผ
0

algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
55/88
post-thumbnail

๐Ÿ’ก Python 3






๐Ÿ”— ๋ฌธ์ œ

๋ฐฉ๋ฌธ ๊ธธ์ด [Link]






๐Ÿ’ป ์ฝ”๋“œ

def solution(dirs):
    d = ['U', 'D', 'R', 'L']
    dx = [0, 0, 1, -1]
    dy = [1, -1, 0, 0]
    
    r = []
    count = 0
    x, y = 0, 0
    for dir in dirs:
        i = d.index(dir)
        if x + dx[i] > 5 or x + dx[i] < -5 or y + dy[i] > 5 or y + dy[i] < -5: continue
        px, py = x, y
        x = x + dx[i]
        y = y + dy[i]
        if [(px, py), (x, y)] in r or [(x, y), (px, py)] in r: 
                continue
        else:
            r.append([(px, py), (x, y)])
            count += 1
    return count






๐Ÿ’ฅ ๋‹ค๋ฅธ ์‚ฌ๋žŒ ์ฝ”๋“œ

set ํ™œ์šฉํ•ด์„œ ์•„๋ž˜์™€ ๊ฐ™์ด ์ฝ”๋“œ๋ฅผ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ํ•  ์ˆ˜ ์žˆ๋‹ค.

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
    return len(s)//2

0๊ฐœ์˜ ๋Œ“๊ธ€