๐Ÿ—๏ธ Algorithm/โฌ› ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

โฌ› [Programmers] [Python] [Level2] ํ”ผ๋กœ๋„

Dbswnstjd 2023. 4. 6. 16:59

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/87946

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

ํ’€์ด

# ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 2๋‹จ๊ณ„ - ํ”ผ๋กœ๋„
from itertools import permutations
from collections import deque
def solution(k, dungeons):
    answer = 0
    
    for p in permutations(dungeons, len(dungeons)):
        tmp = k
        cnt = 0 
        
        for need, spend in p:
            if tmp >= need:
                tmp -= spend
                cnt += 1
        answer = max(answer, cnt)
    return answer
solution(80, [[80,20],[50,40],[30,10]])


#Backtracking
answer = 0
def dfs(k, cnt, dungeons, visited):
    global answer 
    if cnt > answer:
        answer = cnt
    
    for i in range(len(dungeons)):
        if not visited[i] and k >= dungeons[i][0]:
            visited[i] = True
            dfs(k - dungeons[i][1], cnt + 1, dungeons, visited)
            visited[i] = False
        
def solution(k, dungeons):
    global answer
    visited = [False] * len(dungeons)
    dfs(k, 0, dungeons, visited)
    return answer

# BFS
def solution(k, dungeons):
    answer = -1
    queue = deque()
    queue.append((k, []))

    while queue:
        k, route = queue.popleft()
        for i in range(len(dungeons)):
            a, b = dungeons[i]
            if k >= a and i not in route:
                temp = route + [i]
                queue.append((k - b, temp))
            else:
                answer = max(answer, len(route))

    return answer

๋ฐฑํŠธ๋ž˜ํ‚น, BFS, permutation์„ ์ด์šฉํ•˜์—ฌ ํ’€์ด๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.