๊ด€๋ฆฌ ๋ฉ”๋‰ด

๐‘†๐‘ข๐‘›๐‘ โ„Ž๐‘–๐‘›๐‘’ ๐‘Ž๐‘“๐‘ก๐‘’๐‘Ÿ ๐‘Ÿ๐‘Ž๐‘–๐‘›โœง

[Python] ๋ฐฑ์ค€ 1759 & ๋ฐฑ์ค€ 1987 ๋ณธ๋ฌธ

# ๋ฐฑ์ค€ 1759
def solution(depth, index, word):
    if depth == L:
        vo, co = 0, 0
        for w in word:
            if w in 'aeiou':
                vo += 1
            else:
                co += 1
        if vo >= 1 and co >= 2:
            print(word)
            return

    for i in range(index, C):
        solution(depth+1, i+1, word + memo[i])

L, C = map(int, input().split())
memo = list(input().split())
memo.sort()
solution(0, 0, "")
#1987 ์•ŒํŒŒ๋ฒณ

import sys

input = sys.stdin.readline
n, m = map(int, input().split(' ')) # ์„ธ๋กœ, ๊ฐ€๋กœ
graph = [list(map(str, input().rstrip())) for _ in range(n)]
queue = set()

d_row = [0, -1, 0, 1]
d_col = [1, 0, -1, 0]

def bfs():
    word = graph[0][0]
    queue.add((0, 0, word))
    global result
    while queue:
        x, y, word = queue.pop()
        result = max(result, len(word))
        for i in range(4):
            nx = x + d_row[i]
            ny = y + d_col[i]
            if nx <0 or ny < 0 or nx> n-1 or ny > m-1:
                continue
            if graph[nx][ny] in word:
                continue
            queue.add((nx, ny, word+graph[nx][ny]))

result = 0
bfs()
print(result)

queue = deque()๋กœ ํ–ˆ๋”๋‹ˆ ์‹œ๊ฐ„์ดˆ๊ณผใ… ใ… 

set์œผ๋กœ ํ–ˆ๋”๋‹ˆ ์„ฑ๊ณต

 

 

๐Ÿ“ queue vs set

  • deque์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋Š” O(1)
  • set์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋„ O(1)

 

ํ•˜์ง€๋งŒ queue์€ ์ค‘๋ณต์„ ํ—ˆ์šฉํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ค‘๋ณต๋œ ๊ฐ’ ๋„ฃ์–ด๋„ ๊ณ„์‚ฐํ•ด์„œ ์‹œ๊ฐ„์ดˆ๊ณผ๋‚จ

๊ทธ๋ž˜์„œ set์œผ๋กœ ์ค‘๋ณต ํ—ˆ์šฉํ•˜์ง€์•Š์œผ๋ฉด ์‹œ๊ฐ„์ด ๋‹จ์ถ•๋œ๋‹ค.