ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

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

 

programmers.co.kr

 

๋ฌธ์ œ ํ’€์ด

 ์บ๋ฆญํ„ฐ๊ฐ€ [0, 0] ์ขŒํ‘œ์—์„œ ์‹œ์ž‘ํ•ด ๋ช…๋ น์— ๋”ฐ๋ผ ์ƒ, ํ•˜, ์ขŒ, ์šฐ๋กœ ์ด๋™ํ•œ๋‹ค. ์ค‘๋ณตํ•˜์—ฌ ์ด๋™ํ•œ ๊ฑฐ๋ฆฌ์™€ ๋ฒ”์œ„ ๋ฐ–์œผ๋กœ ์ด๋™ํ•œ ๊ฒฝ์šฐ๋ฅผ ์ œ์™ธํ•˜์—ฌ ์ด๋™ํ•œ ๊ฑฐ๋ฆฌ์˜ ํ•ฉ์„ ๊ณ„์‚ฐํ•˜์—ฌ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ํ†ตํ•ด `U, D, L, R`๋กœ ์ด๋™ํ•  ๊ฒฝ์šฐ ๋ณ€ํ™”ํ•˜๋Š” ์ขŒํ‘œ๋ฅผ ์„ ์–ธํ•œ ํ›„, ๋ฒ”์œ„์— ๋”ฐ๋ผ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ `visited`์— ์ถ”๊ฐ€ํ•˜๋ฉด ๋œ๋‹ค.

 

 ๋ฌธ์ œ์—์„œ ๊ตฌํ•˜๊ณ ์ž ํ•˜๋Š” ๋‹ต์€ `visteid // 2`๊ฐ€ ๋œ๋‹ค. ์ด์™€ ๊ฐ™์€ ์ด์œ ๋Š” ์ด๋™ํ•  ๋•Œ๋Š” ์ถœ๋ฐœํ•œ ๊ณณ๊ณผ ๋„์ฐฉํ•œ ๊ณณ ์–‘๋ฐฉํ–ฅ์œผ๋กœ ๊ธฐ๋กํ•˜์—ฌ์•ผ ํ•œ๋‹ค. ์ฆ‰ ํ˜„์žฌ ์ขŒํ‘œ๊ฐ€ `[x, y]` ๋‹ค์Œ ์ขŒํ‘œ๊ฐ€ `[next_x, next_y]`๋ผ๋ฉด `[x, y, next_x, next_y], [next_x, next_y, x, y]`๋ฅผ ๊ธฐ๋กํ•˜์—ฌ์•ผ ํ•œ๋‹ค.

 

์ฝ”๋“œ

move = {
    'U': (-1, 0),
    'D': (1, 0),
    'L': (0, -1),
    'R': (0, 1)
}


def solution(dirs):
    x, y = 0, 0
    visited = set()

    for command in dirs:
        dx, dy = move[command]
        next_x, next_y = x + dx, y + dy

        if 0 <= abs(next_x) <= 5 and 0 <= abs(next_y) <= 5:
            if (x, y, next_x, next_y) not in visited:
                visited.add((x, y, next_x, next_y))
                visited.add((next_x, next_y, x, y))
            x, y = next_x, next_y

    return len(visited) // 2
728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€