๋ชจ๋ ์น๊ตฌ ์ฐพ๊ธฐ ์๊ณ ๋ฆฌ์ฆ
def print_all_friends(g, start):
qu = [] #์ฒ๋ฆฌํด์ผ ํ ์ฌ๋๋ค ์ ์ฅ
done = set() #์ด๋ฏธ ํ์ ์ถ๊ฐํ ์ฌ๋๋ค์ ์งํฉ์ ๊ธฐ๋ก(์ค๋ณต๋ฐฉ์ง)
qu.append(start)
done.add(start)
while qu: #ํ์ ์ฒ๋ฆฌํ ์ฌ๋์ด ๋จ์์๋ ๋์์
p = qu.pop(0)
print(p)
for x in g[p]: #๊ทธ์ ์น๊ตฌ๋ค ์ค์
if x not in done: #์์ง ํ์ ์ถ๊ฐ๋์ ์๋ ์ฌ๋์
qu.append(x)
done.add(x)
fr_info = {
'Summer': ['John', 'Justin', 'Mike'],
'John': ['Summer', 'Justin'],
'Justin': ['John', 'Summer', 'Mike', 'May'],
'Mike': ['Summer', 'Justin'],
'May': ['Justin', 'Kim'],
'Kim': ['May'],
'Tom': ['Jerry'],
'Jerry': ['Tom']
}
print_all_friends(fr_info, 'Summer')
print()
print_all_friends(fr_info, 'Jerry')
๋ชจ๋ ์น๊ตฌ๋ฅผ ์ฐพ์์ ์น๋ฐ๋๋ฅผ ๊ณ์ฐํ๋ ์๊ณ ๋ฆฌ์ฆ
def print_all_friends(g, start):
qu = []
done = set()#์ค๋ณต๋ฐฉ์ง
qu.append((start, 0))#(์ฌ๋์ด๋ฆ, ์น๋ฐ๋) ํํ๋ก ๋ฌถ์ด ์ฒ๋ฆฌ
done.add(start)#์งํฉ์ ์ถ๊ฐ
while qu:
(p, d) = qu.pop(0)#ํ์์ (์ฌ๋์ด๋ฆ, ์น๋ฐ๋)๋ฅผ ๊ฐ๊ฐ ๊บผ๋
print(p, d)
for x in g[p]:#์น๊ตฌ๋ค ์ค์
if x not in done:#์์ง ํ์ ์ถ๊ฐ๋ ์ ์ด ์๋ ์ฌ๋์
qu.append((x, d + 1))#์น๋ฐ๋ 1 ์ฆ๊ฐ์์ผ ํ์ ์ถ๊ฐ
done.add(x)#์งํฉ์๋ ์ถ๊ฐ
fr_info = {
'Summer': ['John', 'Justin', 'Mike'],
'John': ['Summer', 'Justin'],
'Justin': ['John', 'Summer', 'Mike', 'May'],
'Mike': ['Summer', 'Justin'],
'May': ['Justin', 'Kim'],
'Kim': ['May'],
'Tom': ['Jerry'],
'Jerry': ['Tom']
}
print_all_friends(fr_info, 'Summer')
print()
print_all_friends(fr_info, 'Jerry')
'Algorithm > Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python] ๋ฐฑ์ค 1613 - ์ญ์ฌ (1) | 2023.02.05 |
---|---|
[Python] ๋ฐฑ์ค 6118 - ์จ๋ฐ๊ผญ์ง (0) | 2023.02.03 |
[Python] ํ์ ์คํ(queue, stack) (0) | 2020.08.31 |
[Python] ์ด๋ถ ํ์ (0) | 2020.08.26 |
[Python] ํต ์ ๋ ฌ (0) | 2020.08.25 |