2024. 1. 1. 22:41ใCS - Roadmap.sh/1. Data structures
Data structures (with python) - 2. Graph - 2.1. Directed graph
๐ก A directed graph is graph, i.e., a set of objects (called vertices or nodes) that are connected together, where all the edges are directed from one vertex to another. A directed graph is sometimes called a digraph or a directed network. In contrast, a graph where the edges are bidirectional is called an undirected graph.
๋ฐฉํฅ์ฑ ๊ทธ๋ํ๋ ์๋ก ์ฐ๊ฒฐ๋ ๊ฐ์ฒด(์ ์ ๋๋ ๋ ธ๋๋ผ๊ณ ํจ)์ ์งํฉ์ผ๋ก, ๋ชจ๋ ๊ฐ์ฅ์๋ฆฌ๊ฐ ํ ์ ์ ์์ ๋ค๋ฅธ ์ ์ ์ผ๋ก ํฅํ๋ ๊ทธ๋ํ์ ๋๋ค. ๋ฐฉํฅ์ฑ ๊ทธ๋ํ๋ ์ด์ค๊ทธ๋ํ(digraph) ๋๋ ๋ฐฉํฅ์ฑ ๋คํธ์ํฌ๋ผ๊ณ ๋ ๋ถ๋ฆฝ๋๋ค. ์ด์ ๋์กฐ์ ์ผ๋ก, ๊ฐ์ฅ์๋ฆฌ๊ฐ ์๋ฐฉํฅ์ธ ๊ทธ๋ํ๋ฅผ ๋ฌด๋ฐฉํฅ ๊ทธ๋ํ๋ผ๊ณ ํฉ๋๋ค.
with python ์ด๋ ํ์ด์ฌ์์ ๋ฐฉํฅ์ฑ ๊ทธ๋ํ์ ๋ํด ์์๋ด ์๋ค.
ํ์ด์ฌ์์ ๋ฐฉํฅ์ฑ ๊ทธ๋ํ (Directed Graph) ๋ฅผ ๊ตฌํํ๊ณ ํ์ํ๋ ๋ฐฉ๋ฒ.
์ธ์ ๋ฆฌ์คํธ(Adjacency List)์ ์ฌ์ฉํด์ ์ค๋ช ํ๊ฒ ์ต๋๋ค.
(์ธ์ ๋ฆฌ์คํธ ์ถํ ๋ค๋ฃจ๊ธฐ)
class DirectedGraph:
def __init__(self):
self.graph = {}
def add_edge(self, node, neighbour):
if node not in self.graph:
self.graph[node] = [neighbour]
else:
self.graph[node].append(neighbour)
๋จผ์ , ๋ฐฉํฅ์ฑ ๊ทธ๋ํ๋ฅผ ์ ์ฅํ๋ ํด๋์ค๋ฅผ ์์ฑํฉ๋๋ค.
์ด ํด๋์ค๋ ๋ ธ๋๋ค์ ๋ชฉ๋ก์ ์ ์ฅํ๊ณ , ๋ ธ๋๋ค ๊ฐ์ ์ฐ๊ฒฐ ๊ด๊ณ๋ฅผ ๊ด๋ฆฌํฉ๋๋ค.
์์ ์ฝ๋์์ add_edge ๋ฉ์๋๋ฅผ ์ฌ์ฉํด ๋ ธ๋๊ฐ์ ์ฃ์ง๋ฅผ ์ถ๊ฐํ ์ ์์ต๋๋ค.
์ด ๋ฉ์๋๋ ๋ฐฉํฅ์ฑ ์ฃ์ง๋ฅผ ํํํ๋ฏ๋ก, ๋ ธ๋์์ ์ด์ ๋ ธ๋๋ก๋ง ์ฐ๊ฒฐ๋ฉ๋๋ค.
๋ค์์ผ๋ก, ์ด ๊ทธ๋ํ๋ฅผ ๊น์ด ์ฐ์ ํ์(DFS)ํ๋ ๋ฉ์๋๋ฅผ ์ถ๊ฐํด ๋ณด๊ฒ ์ต๋๋ค.
DFS๋ ํ์ฌ ๋ ธ๋์์ ๊ฐ๋ฅํ ๊น๊ฒ ํ์ํ๊ณ , ๋ ์ด์ ๋ฐฉ๋ฌธํ ๋ ธ๋๊ฐ ์์ ๋ ์ด์ ๋ ธ๋๋ก ๋์๊ฐ๋ ๋ฐฉ์์ผ๋ก ์๋ํฉ๋๋ค.
(์ถํ์ DFS, BFS๋ฅผ ๋ค๋ฃน๋๋ค)
def dfs(self, node, visited): # ์ ์ฝ๋์ ์ด์ด์ง๋๋ค ๋ค์ฌ์ฐ๊ธฐ ์ฃผ์
if node not in visited:
visited.append(node)
if node in self.graph:
for neighbour in self.graph[node]:
self.dfs(neighbour, visited)
return visited
์์ ๋ฉ์๋์์ visited๋ ๋ฐฉ๋ฌธํ ๋ ธ๋๋ค์ ๋ชฉ๋ก์ ์ ์ฅํ๋ ๋ฆฌ์คํธ์ ๋๋ค.
์ฌ๊ท์ ์ผ๋ก dfs๋ฉ์๋๋ฅผ ํธ์ถํ์ฌ ๊ทธ๋ํ๋ฅผ ํ์ํฉ๋๋ค.
์ด ํด๋์ค๋ฅผ ์ฌ์ฉํ์ฌ ๋ฐฉํฅ์ฑ ๊ทธ๋ํ๋ฅผ ์์ฑํ๊ณ ํ์ํด ๋ด ์๋ค.
g = DirectedGraph()
g.add_edge('A', 'B')
g.add_edge('A', 'C')
g.add_edge('B', 'D')
g.add_edge('C', 'D')
print(g.dfs('A', [])) # ['A', 'B', 'D', 'C']
์์ ์ฝ๋์์ 'A' ๋ ธ๋์์ ์์ํ์ฌ DFS๋ฅผ ์ํํ๋ฉด, 'B', 'D', 'C'์์๋ก ๋ ธ๋๋ฅผ ๋ฐฉ๋ฌธํ๊ฒ ๋ฉ๋๋ค.
'CS - Roadmap.sh > 1. Data structures' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Data structures (with python) - 3. Heap (0) | 2024.01.05 |
---|---|
Data structures (with python) - 2. Graph - 2.4. Graph Representation (1) | 2024.01.04 |
Data structures (with python) - 2. Graph - 2.3. Spanning Tree (1) | 2024.01.03 |
Data structures (with python) - 2. Graph - 2.2. Undirected graph (0) | 2024.01.02 |
Data structures (with python) - 1. Array (0) | 2024.01.01 |