[TIL_Carrotww] 55 - 22/11/18

์œ ํ˜•์„ยท2022๋…„ 11์›” 18์ผ
0

python/Algorithm

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

๐Ÿ“Carrotww์˜ ์ฝ”๋”ฉ ๊ธฐ๋ก์žฅ

๐Ÿงฒ python algorithm

๐Ÿ” programmers ๋ถ€๋Œ€๋ณต๊ท€ level3
์–ด์ œ ํ’€๋˜ ๋ฌธ์ œ๋‹ค.
๋ชป ํ’€์—ˆ์—ˆ๋Š”๋ฐ ํ•œ ๊ฐ€์ง€๋ฅผ ๋” ์ƒ๊ฐํ•˜์ง€ ๋ชป ํ–ˆ๋‹ค.
sources ๋ฅผ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ๋Œ๋ฆฌ๊ธฐ ๋ณด๋‹ค destination์„ ์ถœ๋ฐœ์ง€๋กœ ์žก์œผ๋ฉด ๋ชจ๋“  ์ถœ๋ฐœ์ง€์™€์˜ ๊ฑฐ๋ฆฌ๊ฐ€ ๋‚˜์˜ค๋Š”๊ฑฐ๊ฑฐ๋Š˜...
์ด ์‚ฌ์‹ค์„ ๊นจ๋‹ฌ์•˜์„๋•Œ ์ง„์งœ... ๋„ˆ๋ฌด... ์•„์‰ฌ์› ๋‹ค.
๋ฐ‘์—๋Š” ๋‚˜์˜ ํ’€์ด์ด๋‹ค.

  • ํ’€์ด
from collections import deque, defaultdict

def solution(n, roads, sources, destination):
    roads_path = defaultdict(list)
    for a, b in roads:
        roads_path[a].append(b)
        roads_path[b].append(a)

    queue = deque([destination])
    visited = {x:-1 for x in range(1, n+1)}
    visited[destination] = 0
    while queue:
        cur_road = queue.popleft()
        cur_dis = visited[cur_road]
        for nxt_road in roads_path[cur_road]:
            if visited[nxt_road] == -1:
                visited[nxt_road] = cur_dis + 1
                queue.append(nxt_road)
    return [visited[x] for x in sources]

์–ด์ œ์™€ ๊ฐ™์ด visited key ๊ฐ’์—๋Š” n์˜ ๊ฐœ์ˆ˜๋งŒํผ ์ดˆ๊ธฐํ™” ํ•ด์ฃผ๊ณ  value ๋Š” -1๋กœ ์ดˆ๊ธฐํ™” ํ•ด์ฃผ์—ˆ๋‹ค.
๋ฐฉ๋ฌธํ•œ ๊ธธ์€ 0์œผ๋กœ ๋ฐ”๊พธ์–ด ์ฃผ์—ˆ๋‹ค.

return ๊ฐ’์€ visited์—์„œ sources์— ๋‹ด๊ฒจ์žˆ๋Š” ์ˆซ์ž๋“ค๋งŒ ๋ฝ‘์•„์„œ result์— ๋‹ด์•„์ฃผ์—ˆ๋‹ค.

์‚ด์ง ๊ผฐ ๋ฌธ์ œ์ด์ง€๋งŒ ์ž˜ ์ƒ๊ฐํ•ด๋ณด๋ฉด ํ’€ ์ˆ˜ ์žˆ์—ˆ๋˜ ๋ฌธ์ œ์˜€๋‹ค.
๋‚˜ ์ฒ˜๋Ÿผ ํ•œ ์ƒ๊ฐ์˜ ํ‹€ ์•ˆ์— ๊ฐ‡ํžˆ๋Š” ๊ฒƒ ๋งŒ ์•„๋‹ˆ์˜€๋‹ค๋ฉด..ใ… 

ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค 10~15 ๋ฒˆ ๊ณผ ๊ฐ™์ด ๊ตฌ์กฐ์ ์œผ๋กœ bfs ์˜ ์ถœ๋ฐœ์ง€๊ฐ€ ์—ฌ๋Ÿฌ ๊ณณ ์ด์˜€๋‹ค๋ฉด ํ’€ ์ˆ˜ ์—†๋Š” ๋ฌธ์ œ์˜€๋‹ค.

์˜ค๋Š˜ ๋!

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