BFS์ DFS๋ฅผ ๊ฐ๋ ๊ณผ ์ค์ต ๋ฌธ์ ๋ฅผ ๋ณต์ตํ๊ณ ๋ฐฑ์ค ๋ฌธ์ ๋ฅผ ํตํด ์ค์ ๋ฌธ์ ์ ์ ์ฉํด๋ด์ผ๋ก์จ
๋์ ์ฐจ์ด์ ์๊ณ ๋ฆฌ์ฆ ๋์๋ฐฉ์์ ๋ํด ํ์คํ๊ฒ ์๋ ๊ณ๊ธฐ๊ฐ ๋์๋ค.
1. ์ด์ ๋ ธ๋ ์ฐพ๊ธฐ (๊ทธ๋ํ ๊ธฐ๋ณธ)
def main():
n, m = map(int, input().split())
node = list(input().split())
node_dict = dict()
for i in range(n):
node_dict[node[i]] = []
for i in range(m):
srt, dst = input().split()
if dst not in node_dict[srt]:
node_dict[srt].append(dst)
find_node = input()
print(len(node_dict[find_node]))
if __name__ == "__main__":
main()
2. BFS (๋๋น ์ฐ์ ํ์)
def bfs(node_dict, node):
visit = []
queue = []
queue.append(node)
while queue:
element = queue.pop(0)
if element not in visit:
visit.append(element)
queue.extend(node_dict[element])
return visit
def main():
n, m = map(int, input().split())
node = list(input().split())
node_dict = dict()
for i in range(n):
node_dict[node[i]] = []
for i in range(m):
srt, dst = input().split()
if dst not in node_dict[srt]:
node_dict[srt].append(dst)
find_node = input()
print(*bfs(node_dict, find_node))
if __name__ == "__main__":
main()
3. DFS (๊น์ด ์ฐ์ ํ์)
def dfs(node_dict, node, visit = None):
if visit is None:
visit = []
visit.append(node)
for element in node_dict[node]:
if element not in visit:
dfs(node_dict, element, visit)
return visit
def main():
n, m = map(int, input().split())
node = list(input().split())
node_dict = dict()
for i in range(n):
node_dict[node[i]] = []
for i in range(m):
srt, dst = input().split()
if dst not in node_dict[srt]:
node_dict[srt].append(dst)
find_node = input()
print(*dfs(node_dict, find_node))
if __name__ == "__main__":
main()
4. 1260๋ฒ DFS์ BFS
def dfs(node, v, visit = None):
if visit == None:
visit = []
visit.append(v)
for element in node[v]:
if element not in visit:
dfs(node, element, visit)
return visit
def bfs(node, v):
visit = []
queue = []
queue.append(v)
while queue:
element = queue.pop(0)
if element not in visit:
visit.append(element)
queue.extend(node[element])
return visit
def main():
n, m, v = map(int, input().split())
node = dict()
for i in range(n):
node[i+1] = []
for i in range(m):
srt, dst = map(int, input().split())
if dst not in node[srt]:
node[srt].append(dst)
if srt not in node[dst]:
node[dst].append(srt)
for i in range(n):
node[i+1].sort()
print(*dfs(node, v))
print(*bfs(node, v))
if __name__ == "__main__":
main()
์๋ฐฉํฅ ๊ทธ๋ํ์ ์ฃผ์ํด์ผํ๋ค.
- ๊นํ๋ธ -
github.com/k906506/2020_Winter_Assemble-And-selfcode
'โน๏ธ ๋ผ์ดํ > 2020 ๊ฒจ์ธ๋ฐฉํ ๋ชจ๊ฐ์ฝ(๊ฐ์ธ)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์ฝ๋ ํ๊ตฌ๋ง ํ] 2020.01.05(ํ) - 3์ฃผ์ฐจ ๊ฐ์ธ ๊ฒฐ๊ณผ (0) | 2021.01.05 |
---|---|
[์ฝ๋ ํ๊ตฌ๋ง ํ] 2021.01.05(ํ) - 3์ฃผ์ฐจ ๊ฐ์ธ ๋ชฉํ (0) | 2021.01.05 |
[์ฝ๋ ํ๊ตฌ๋ง ํ] 2020.12.30(์) - 2์ฃผ์ฐจ ๊ฐ์ธ ๊ฒฐ๊ณผ (0) | 2020.12.30 |
[์ฝ๋ ํ๊ตฌ๋ง ํ] 2020.12.30(์) - 2์ฃผ์ฐจ ๊ฐ์ธ ๋ชฉํ (0) | 2020.12.30 |
[์ฝ๋ ํ๊ตฌ๋ง ํ] 2020.12.23(์) - 1์ฃผ์ฐจ ๊ฐ์ธ ๋ชฉํ (0) | 2020.12.23 |