π‘ DFS(Depth First Search)
: κΉμ΄ μ°μ νμ → κ·Έλνμμ κΉμ λΆλΆμ μ°μ μ μΌλ‘ νμνλ μκ³ λ¦¬μ¦
λ―Έλ‘μ κ°νμ λ, κ°λ κΈΈμ΄ λ§νλ©΄ κ°μ₯ μ΅κ·Όμ μμλ κ°λ¦ΌκΈΈλ‘ λλμκ°λ€ → μ€ν μ°μ κ°λ₯
** μ€νμ μ§λμ¨ κ²½λ‘λ₯Ό μ μ₯νμ **
- νμ μμ λ Έλλ₯Ό μ€νμ push → λ°©λ¬Έ μ²λ¦¬
- μ€νμ΄ κ³΅λ°±μ΄ μλλ©΄ νλμ μμΉλ₯Ό κΊΌλ → νμ¬ μμΉ → λ°©λ¬Έ μ²λ¦¬
- κΊΌλΈ νμ¬ μμΉκ° μΆκ΅¬ → νμ μ±κ³΅ μΆκ΅¬κ° μλλ€ → μνμ’μ° μ΄μν λ°©λ€μ μ΄ν΄λ΄ → κ° μ μλ λͺ¨λ λ°©λ€μ μ€νμ push → λ°λ³΅
O(N)μ μκ°μ΄ μμλκ³ , DFSλ μ€νμ μ¬μ©νλ μκ³ λ¦¬μ¦ → μ€μ ꡬνμ μ¬κ· ν¨μλ₯Ό μ΄μ©νμ λ λ§€μ° κ°κ²°νκ² κ΅¬νν μ μλ€.
[ꡬν]
graph = [[], [2, 3, 8], [1, 7, 8], [1, 4, 5], [3, 5], [3, 4], [7], [6, 8], [1, 7]]
visited = [False] * 9
def dfs(Graph, v, Visited):
Visited[v] = True
print(v, end=' ')
for i in Graph[v]:
if Visited[i] is False:
dfs(Graph, i, Visited)
dfs(graph, 1, visited)
[νμ© μμ ]
N, M = map(int, input().split())
graph = []
for i in range(N):
graph.append(list(map(int, input())))
def dfs(x, y):
if x < 0 or x >= N or y < 0 or y >= M:
return False
if graph[x][y] == 0:
graph[x][y] = 1
dfs(x - 1, y)
dfs(x, y - 1)
dfs(x + 1, y)
dfs(x, y + 1)
return True
return False
result = 0
for i in range(N):
for j in range(M):
if dfs(i, j) is True:
result += 1
print(result)
π‘ BFS(Breadth First Search)
: λλΉ μ°μ νμ → κ°κΉμ΄ λ ΈλλΆν° νμνλ μκ³ λ¦¬μ¦
** μΈμ ν λ Έλλ₯Ό λ°λ³΅μ μΌλ‘ νμ λ£μ΄μ νμ **
- νμ μμ λ Έλλ₯Ό νμ λ£μ → λ°©λ¬Έ μ²λ¦¬
- νμμ λ Έλλ₯Ό κΊΌλ΄ ν΄λΉ λ Έλμ μΈμ λ Έλ μ€μμ λ°©λ¬Ένμ§ μμ λ Έλλ₯Ό λͺ¨λ νμ λ£μ → λ°©λ¬Έ μ²λ¦¬
- μμ κ³Όμ λ°λ³΅
O(N)μ μκ°μ΄ μμλλ©°, μΌλ°μ μΈ κ²½μ° μ€μ μν μκ°μ DFSλ³΄λ€ μ’μ νΈμ΄λ€.
[ꡬν]
from collections import deque
graph = [[], [2, 3, 8], [1, 7, 8], [1, 4, 5], [3, 5], [3, 4], [7], [6, 8], [1, 7]]
visited = [False] * 9
def bfs(Graph, s, Visited):
# νμ μμ λ
Έλλ₯Ό νμ λ£μ
queue = deque([s])
Visited[s] = True # λ°©λ¬Έ μ²λ¦¬
while queue :
v = queue.popleft()
print(v, end=' ')
for i in Graph[v]:
# μΈμ λ
Έλ μ€μμ λ°©λ¬Ένμ§ μμ λ
Έλλ₯Ό λͺ¨λ νμ λ£μ
if Visited[i] is False:
queue.append(i)
Visited[i] = True # λ°©λ¬Έ μ²λ¦¬
bfs(graph, 1, visited)
[νμ© μμ ]
N, M = map(int, input().split())
graph = []
for i in range(N):
graph.append(list(map(int, input())))
def dfs(x, y):
if x < 0 or x >= N or y < 0 or y >= M:
return False
if graph[x][y] == 0:
graph[x][y] = 1
# μνμ’μ°λ₯Ό μ΄νΌλ©° λ°©λ¬Ένμ§ μμ μ§μ μ°ΎκΈ°
dfs(x - 1, y)
dfs(x, y - 1)
dfs(x + 1, y)
dfs(x, y + 1)
return True
return False
result = 0
for i in range(N):
for j in range(M):
if dfs(i, j) is True:
result += 1
print(result)