[Alg] DFS / BFS

2023. 1. 11. 22:19·Algorithm



 





DFS : 재귀함수(스택)로 구현
재귀 함수 실행 시 방문처리 & 값 이용
연결된 노드 재귀함수 호출

 

# DFS
# 동작 원리 : 스택
# 구현 방법 : 재귀 함수 이용
# 실제로는 스택을 쓰지 않아도 되며 탐색을 수행함에 있어서 데이터의 개수가 N개인 경우 O(N)의 시간 소모됨

# visited 리스트가 dfs 함수 안에 있으면, dfs 함수가 재귀적으로 호출되면서 계속 리스트가 초기화되기 때문에 안됨
# vertex : 정점, edge : 간선

graph = [[],[2,3,8],[1,7],[1,4,5],[3,5],[3,4],[7],[2,6,8],[1,7]]
visited = [0 for _ in range(len(graph))]

def dfs(graph, visited, v):
    if visited[v] == 0: 
        visited[v] = 1 
        print(v, end=" ")
        for x in graph[v]:
            dfs(graph, visited, x)
dfs(graph, visited, 1)




 



BFS : queue로 구현
queue에 넣으며 방문처리
queue에서 빼며 값 이용/ 연결된 노드 넣으며 방문처리

 

# BFS
# 동작 원리 : 큐
# 구현 방법 : 큐 자료구조 이용

class Queue:
    def __init__(self):
        self.__queue = []
        self.__size = 0
    def enqueue(self,x):
        self.__queue.insert(0,x)
        self.__size += 1
    def dequeue(self):
        self.__size -= 1
        return self.__queue.pop()
    def dequeueAll(self):
        self.__queue = []
        self.__size = 0
    def isEmpty(self):
        return self.__size == 0


graph = [[],[2,3,8],[1,7],[1,4,5],[3,5],[3,4],[7],[2,6,8],[1,7]]
visited = [0 for _ in range(len(graph))]

def bfs(graph, visited, v):
    queue = Queue()
    queue.enqueue(v)
    visited[v] = 1
    while True:
        if queue.isEmpty(): break
        v = queue.dequeue(); print(v, end=" ")
        for x in graph[v]:
            if visited[x] == 0:
                queue.enqueue(x)
                visited[x] = 1

bfs(graph, visited, 1)
'Algorithm' 카테고리의 다른 글
  • [Alg] 위상 정렬 (Topology Sort)
  • [Alg] 서로소 집합 알고리즘 (Disjoint Sets Algorithm)
  • [Alg] GCD 계산 알고리즘
  • [Alg] 소수(Prime Number)인지 판별하는 방법
vysryoo
vysryoo
  • vysryoo
    vysryoo
    vysryoo
  • 전체
    오늘
    어제
    • 분류 전체보기 (129)
      • Python (20)
      • Data structure (12)
      • Algorithm (14)
      • Operating system (18)
      • Programming language theory (12)
      • Computer architecture (6)
      • Softeware engineering (8)
      • Multicore (2)
      • Data Base (3)
      • Problem solving (24)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
vysryoo
[Alg] DFS / BFS
상단으로

티스토리툴바