๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/Programmers

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

 

 

 

ํ•ด์„ค ์ฝ”๋“œ 

 

def solution(dirs):
    visit = set()
    x = 0; y = 0
    for d in dirs:
        if d == 'U' and y < 5:
            visit.add(((x, y), (x, y+1)))
            y += 1
            
        elif d == 'D' and y > -5:
            visit.add(((x, y-1), (x, y)))
            y -= 1
            
        elif d == 'R' and x < 5:
            visit.add(((x, y), (x+1, y)))
            x += 1
            
        elif d == 'L' and x > -5:
            visit.add(((x-1, y), (x, y)))
            x -= 1
    return len(visit)
๋ถ„์„ > set ์„ ํ™œ์šฉํ•ด ์š”์†Œ๋ฅผ ์ถ”๊ฐ€ํ•˜๋Š” ๋ฒ•์„ ๋ฐฐ์› ๋‹ค. set์„ ํ™œ์šฉํ•˜๋ฉด ๊ฐ™์€ ๊ธธ์„ ๊ฑธ์—ˆ๋Š”์ง€, ์•„๋‹Œ์ง€๋ฅผ ๋ถ„๋ณ„ํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ธธ์€ ์–‘๋ฐฉํ–ฅ(ํ˜„์œ„์น˜์™€ ์ „์œ„์น˜๊ฐ€ ๋ฐ˜์ „๋˜์–ด์•ผ ๊ฐ™์€ ๊ธธ์„ ๊ฑธ์€ ๊ฒƒ)์ด๊ธฐ ๋•Œ๋ฌธ์— x์™€ y๋ฅผ ๊ฐ๊ฐ ์™ผ์ชฝ, ์˜ค๋ฅธ์ชฝ์œผ๋กœ ๋‚˜๋ˆ„์–ด ๊ณ„์‚ฐํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค. ํ•œ์ชฝ์—๋งŒ ๋ชฐ์•„์„œ ๊ณ„์‚ฐํ•ด์ค€๋‹ค๋ฉด, set ๋ฐฐ์—ด์ด ์ค‘๋ณต์„ ๊ฑฐ๋ฅด์ง€ ๋ชปํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. 

 

 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋ฐฉ๋ฌธ ๊ธธ์ด

 

programmers.co.kr