본문 바로가기

자료구조48

[알고리즘] 프로그래머스 | 단어변환 단어 변환 답: 더보기 온전히 함수로 분리해 풀이하기 from collections import deque def bfs(begin, target, words): q = deque() q.append((begin, 0)) while q: start_word, step = q.popleft() if start_word == target: return step for word in words: count = 0 for i in range(len(word)): if word[i] != start_word[i]: count += 1 if count == 1: q.append((word, step+1)) def solution(begin, target, words): if not target in words: r.. 2023. 11. 2.
[알고리즘] 프로그래머스 | 이중우선순위큐 이중우선순위큐 답: 더보기 힙 하나로 구현하기 from heapq import heappush, heappop def solution(operations): heap = [] for operate in operations: o = operate.split(" ") alpha, num = o[0], int(o[1]) if alpha == "I": heappush(heap, num) elif alpha == "D": if heap and num == -1: heappop(heap) elif heap and num == 1: heap.pop() if len(heap) > 0: return [max(heap), heap[0]] return [0,0] min_heap, max_heap으로 구현하기 from hea.. 2023. 10. 27.
[알고리즘] DFS, BFS | 2667 단지번호 붙이기, 2606 바이러스 단지번호 붙이기 답: 더보기 BFS 풀이 from sys import stdin from collections import deque input = stdin.readline N = int(input()) graph = [] for _ in range(N): line = list(map(int, input().strip())) graph.append(line) # {위, 아래, 오른쪽, 왼쪽} 상하좌우 dx = [0, 0, 1, -1] #(0, 1) (0, -1) (1, 0) (-1, 0) dy = [1, -1, 0, 0] def bfs(graph, x, y): queue = deque() # 무엇으로 시작해야하나? x랑 y를 제공해주기 queue.append((x, y)) # 탐색 중 1인 부분은 0으.. 2023. 10. 14.
[알고리즘] 백준 | 1991 트리 순회, 14244 트리만들기 트리 순회 답: 더보기 # 전위 순회 def preorder(root): if root != ".": # {'A': ['B', 'C']} print(root, end="") preorder(tree[root][0]) preorder(tree[root][1]) # 중위 순회 def inorder(root): if root != ".": inorder(tree[root][0]) print(root, end="") inorder(tree[root][1]) # 후위 순회 def postorder(root): if root != ".": postorder(tree[root][0]) postorder(tree[root][1]) print(root, end="") N = int(input()) tree = {} fo.. 2023. 9. 20.