← 목차로 돌아가기 / Back to Index

🧪 Ch14. 동적 프로그래밍 — 실습 코드 / Lab Code: Dynamic Programming

자료구조와 알고리즘 실습 | Data Structures & Algorithms Lab

💡 학습 팁: 코드를 직접 타이핑하면서 익히세요! 숨겨진 코드는 버튼을 눌러 확인하기 전에 먼저 스스로 생각해 보세요.
💡 Study Tip: Type the code yourself to learn! Try to think about hidden sections before revealing them.

📘 교재 예제 (Code)

📘 Textbook Examples (Code)

Code14-01.py

배낭 문제를 동적 프로그래밍으로 해결합니다

## 함수 선언 부분 ##
def knapsack():
## 전역 변수 선언 부분 ##
maxWeight = 7	# 배낭 최대 무게
rowCount = 4	# 보석 숫자
weight = [0, 6, 4,3, 5]   # 보석 무게 (0, 금괴, 수정, 루비, 진주)
money =  [0,13, 8, 6, 12] # 보석 가격 (0, 금괴, 수정, 루비, 진주)

## 메인 코드 부분 ##
Code14-01.py

Solves the knapsack problem using dynamic programming

## Function Declarations ##
def knapsack():
## Global Variables ##
maxWeight = 7	# Max knapsack weight
rowCount = 4	# Number of jewels
weight = [0, 6, 4,3, 5]   # Jewel weights (0, GoldBar, Crystal, Ruby, Pearl)
money =  [0,13, 8, 6, 12] # Jewel values (0, GoldBar, Crystal, Ruby, Pearl)

## Main Code ##
maxValue = knapsack()
print()
print('Max jewel value for knapsack -->', maxValue, '(hundred million won)')
Code14-02.py

금광 찾기를 동적 프로그래밍으로 해결합니다

## 함수 선언 부분 ##
def growRich() :
## 전역 변수 선언 부분 ##
ROW, COL = 5, 5
goldMaze = [[1, 4, 4, 2, 2],
	      [1, 3, 3, 0, 5],
	      [1, 2, 4, 3, 0],
	      [3, 3, 0, 4, 2],
	      [1, 3, 4, 5, 3]]

## 메인 코드 부분 ##
Code14-02.py

Solves the gold mine problem using dynamic programming

## Function Declarations ##
def growRich() :
## Global Variables ##
ROW, COL = 5, 5
goldMaze = [[1, 4, 4, 2, 2],
	      [1, 3, 3, 0, 5],
	      [1, 2, 4, 3, 0],
	      [3, 3, 0, 4, 2],
	      [1, 3, 4, 5, 3]]

## Main Code ##
macolGold = growRich()
print('Max gold collected in maze -->', macolGold)

📗 응용 예제 (Ex)

📗 Applied Examples (Ex)

Ex14-01.py

미로 탐색을 동적 프로그래밍으로 해결합니다

## 함수 선언 부분 ##
def printMaze(arr) :
def growRich() :
## 전역 변수 선언 부분 ##
ROW, COL = 5, 5
goldMaze = [[1, 4, 4, 2, 2],
	[1, 3, 3, 0, 5],
	[1, 2, 4, 3, 0],
	[3, 3, 0, 4, 2],
	[1, 3, 4, 5, 3]]

## 메인 코드 부분 ##

Ex14-01.py

Solves maze navigation using dynamic programming

## Function Declarations ##
def printMaze(arr) :
def growRich() :
## Global Variables ##
ROW, COL = 5, 5
goldMaze = [[1, 4, 4, 2, 2],
	[1, 3, 3, 0, 5],
	[1, 2, 4, 3, 0],
	[3, 3, 0, 4, 2],
	[1, 3, 4, 5, 3]]

## Main Code ##
macolGold = growRich()
print('Max gold collected -->', macolGold)


Ex14-02.py

재귀 vs 메모이제이션 피보나치의 성능을 비교합니다

## 함수 선언 부분 ##
def recu_fibo(n) :
def dp_fibo(n):
## 전역 변수 선언 부분 ##
count_dp, count_recu = 0, 0

## 메인 코드 부분 ##
Ex14-02.py

Compares recursive vs. memoized Fibonacci performance

## Function Declarations ##
def recu_fibo(n) :
def dp_fibo(n):
## Global Variables ##
count_dp, count_recu = 0, 0

## Main Code ##
print(' ## 30th Fibonacci sequence ##')

res = recu_fibo(30)
print('Recursive method --> answer:', res, ', iterations: ', count_recu)

res = dp_fibo(30)
print('DP method --> answer:', res, ', iterations: ', count_dp)

📙 자가 실습 (Self)

📙 Self Practice (Self)

Self14-01.py

배낭 문제를 직접 구현합니다

# ## 함수 선언부
def knapsack():
## 전역 변수부
maxWeight = 7  # 배낭 최대 무게
rowCount = 4 # 보석 숫자
weight = [0, 5, 3, 6, 4]   # 보석 무게 (0, 진주, 루비, 금괴, 수정)
money =  [0, 12, 6, 13, 8] # 보석 가격 (0, 진주, 루비, 금괴, 수정)

## 메인 코드부
Self14-01.py

Implements the knapsack problem yourself

# ## Function Declarations
def knapsack():
## Global Variables
maxWeight = 7  # Max knapsack weight
rowCount = 4 # Number of jewels
weight = [0, 5, 3, 6, 4]   # Jewel weights (0, Pearl, Ruby, GoldBar, Crystal)
money =  [0, 12, 6, 13, 8] # Jewel values (0, Pearl, Ruby, GoldBar, Crystal)

## Main Code
maxValue = knapsack()
print()
print('Max jewel value for knapsack -->', maxValue, '(hundred million won)')
Self14-02.py

금광 찾기를 직접 구현합니다

## 함수 선언부
def growRich() :
## 전역 변수부
ROW, COL = 5, 5
goldMaze = [    [1, 4, 4, 2, 2],
                [1, 3, 3, 0, 5],
                [1, 2, 4, 3, 0],
                [3, 3, 0, 4, 2],
                [1, 3, 4, 5, 3]   ]

## 메인 코드부
Self14-02.py

Implements the gold mine problem yourself

## Function Declarations
def growRich() :
## Global Variables
ROW, COL = 5, 5
goldMaze = [    [1, 4, 4, 2, 2],
                [1, 3, 3, 0, 5],
                [1, 2, 4, 3, 0],
                [3, 3, 0, 4, 2],
                [1, 3, 4, 5, 3]   ]

## Main Code
macolGold = growRich()
print('Min thumbtacks in maze -->', macolGold)