[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๊ฐ€์žฅ ๋จผ ๋…ธ๋“œ / ํŒŒ์ด์ฌ / python / BFS
Algorithm/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๊ฐ€์žฅ ๋จผ ๋…ธ๋“œ / ํŒŒ์ด์ฌ / python / BFS

728x90
๋ฐ˜์‘ํ˜•

 

๐Ÿ’ก solutions  

๐Ÿ’ฌ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ๋กœ์ง์„ ์œ„ํ•ด BFS ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ ๊ตฌํ˜„ํ•œ๋‹ค. -> deque ์ž๋ฃŒ๊ตฌ์กฐ ์‚ฌ์šฉ

๐Ÿ’ฌ visit ๋ฐฐ์—ด์„ ๊ฐ€์ง€๊ณ  ๋ฐฉ๋ฌธํ–ˆ๋Š”์ง€ ํ™•์ธํ•จ๊ณผ ๋™์‹œ์— 1๋ถ€ํ„ฐ ํ•ด๋‹น ๋…ธ๋“œ๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ๋ฅผ ์ €์žฅํ•œ๋‹ค.

 

๐Ÿ‘จ‍๐Ÿ’ป code  

from collections import deque


def solution(n, edge):

    adj = [[] for _ in range(n+1)]
    visit = [0] * (n+1)
    for a, b in edge:
        adj[a].append(b)
        adj[b].append(a)
    
    visit[1] = 1
    q = deque([1])
    
    while q:
        x = q.popleft()
        for next in adj[x]:
            if not visit[next]:
                visit[next] = visit[x] + 1
                q.append(next)
    
    max_v = max(visit)
    cnt = visit.count(max_v)

    return cnt if cnt > 0 else 1

 

 

๐Ÿ“Œ problem  

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๊ฐ€์žฅ ๋จผ ๋…ธ๋“œ

6 [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]] 3

programmers.co.kr


๋ฌธ์ œ ์„ค๋ช…

n๊ฐœ์˜ ๋…ธ๋“œ๊ฐ€ ์žˆ๋Š” ๊ทธ๋ž˜ํ”„๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐ ๋…ธ๋“œ๋Š” 1๋ถ€ํ„ฐ n๊นŒ์ง€ ๋ฒˆํ˜ธ๊ฐ€ ์ ํ˜€์žˆ์Šต๋‹ˆ๋‹ค. 1๋ฒˆ ๋…ธ๋“œ์—์„œ ๊ฐ€์žฅ ๋ฉ€๋ฆฌ ๋–จ์–ด์ง„ ๋…ธ๋“œ์˜ ๊ฐฏ์ˆ˜๋ฅผ ๊ตฌํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ๊ฐ€์žฅ ๋ฉ€๋ฆฌ ๋–จ์–ด์ง„ ๋…ธ๋“œ๋ž€ ์ตœ๋‹จ๊ฒฝ๋กœ๋กœ ์ด๋™ํ–ˆ์„ ๋•Œ ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜๊ฐ€ ๊ฐ€์žฅ ๋งŽ์€ ๋…ธ๋“œ๋“ค์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.

๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜ n, ๊ฐ„์„ ์— ๋Œ€ํ•œ ์ •๋ณด๊ฐ€ ๋‹ด๊ธด 2์ฐจ์› ๋ฐฐ์—ด vertex๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, 1๋ฒˆ ๋…ธ๋“œ๋กœ๋ถ€ํ„ฐ ๊ฐ€์žฅ ๋ฉ€๋ฆฌ ๋–จ์–ด์ง„ ๋…ธ๋“œ๊ฐ€ ๋ช‡ ๊ฐœ์ธ์ง€๋ฅผ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.

์ œํ•œ์‚ฌํ•ญ
  • ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜ n์€ 2 ์ด์ƒ 20,000 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • ๊ฐ„์„ ์€ ์–‘๋ฐฉํ–ฅ์ด๋ฉฐ ์ด 1๊ฐœ ์ด์ƒ 50,000๊ฐœ ์ดํ•˜์˜ ๊ฐ„์„ ์ด ์žˆ์Šต๋‹ˆ๋‹ค.
  • vertex ๋ฐฐ์—ด ๊ฐ ํ–‰ [a, b]๋Š” a๋ฒˆ ๋…ธ๋“œ์™€ b๋ฒˆ ๋…ธ๋“œ ์‚ฌ์ด์— ๊ฐ„์„ ์ด ์žˆ๋‹ค๋Š” ์˜๋ฏธ์ž…๋‹ˆ๋‹ค.
์ž…์ถœ๋ ฅ ์˜ˆ
6 [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]] 3
์ž…์ถœ๋ ฅ ์˜ˆ ์„ค๋ช…

์˜ˆ์ œ์˜ ๊ทธ๋ž˜ํ”„๋ฅผ ํ‘œํ˜„ํ•˜๋ฉด ์•„๋ž˜ ๊ทธ๋ฆผ๊ณผ ๊ฐ™๊ณ , 1๋ฒˆ ๋…ธ๋“œ์—์„œ ๊ฐ€์žฅ ๋ฉ€๋ฆฌ ๋–จ์–ด์ง„ ๋…ธ๋“œ๋Š” 4,5,6๋ฒˆ ๋…ธ๋“œ์ž…๋‹ˆ๋‹ค.




๋ฐ˜์‘ํ˜•