๊ณจ๋“œ4 : ์™„์ „ ํƒ์ƒ‰ ๋ฌธ์ œ์ด๋‹ค.

ํ’€์ด

์ด๊ฒŒ ์ „๋‚ ์— ๊ธ‰ํ•˜๊ฒŒ ์งœ๋‹ค๊ฐ€ ์กฐ๊ฑด์„ ๋†“์นœ ๋ฌธ์ œ์ธ๋ฐ, ์˜ค๋Š˜์˜ ์ฒซ๋ฌธ์ œ๋กœ ๋„์ „ํ•ด๋ณด์•˜๋‹ค. ๋‚œ BFS๋กœ ๋ฌธ์ œ ํ’€์ด๋ฐฉํ–ฅ์„ ์ •ํ–ˆ๋Š”๋ฐ, ๋ฌธ์ œ๊ฐ€ ๋ฐฉ๋ฌธ์ด ์ค‘๋ณต์œผ๋กœ ์ผ์–ด๋‚œ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค. ์ฒ˜์Œ์—๋Š” ์ด์ „์˜ ๋ฐœํŒ๋“ค์„ ๊ธฐ์–ตํ•˜๊ณ  ์˜ค๋‹ˆ๊นŒ, ๊ฐ๊ฐ์— ๋„์ฐฉํ•˜๋Š” ๋ฐฉ๋ฒ•์˜์ˆ˜๊ฐ€ ๋‹ค๋ฅด๊ธฐ ๋•Œ๋ฌธ์— ๋ฌธ์ œ๊ฐ€ ์—†์„ ๊ฒƒ์ด๋ผ ์ƒ๊ฐํ–ˆ๋‹ค. ํ•˜์ง€๋งŒ ์•„๋ž˜์˜ ๊ฒฝ์šฐ ์ค‘๋ณต์ด ๋งค์šฐ ๋งŽ์ด ๋ฐœ์ƒํ•  ์—ฌ์ง€๊ฐ€ ์žˆ๋‹ค.

ABEA
BCDE
ADEF

์ด ๋ฌธ์ œ๋Š” ๊ฒฐ๊ตญ, ํŠน์ • ์ง€์—ญ์— ์ตœ์†Œ๋กœ ๋ช‡๋ฒˆ๋งŒ์— ๋„์ฐฉํ–ˆ๋ƒ๊ฐ€ ๊ถ๊ธˆํ•œ ๊ฒƒ์ด ์•„๋‹ˆ๊ณ , ๊ทธ๋ƒฅ ์–˜๊ฐ€ ๋ฐŸ๊ณ  ์ง€๋‚˜์˜จ ๊ฒƒ์ด ์–ด๋–ค ๊ฒƒ์ด๋ƒ, ๊ทธ๋ฆฌ๊ณ  ๊ทธ๊ฒŒ ๊ธธ์ด๊ฐ€ ์–ผ๋งˆ๋ƒ๊ฐ€ ์ค‘์š”ํ•œ ๋ฌธ์ œ์ด๋‹ค. ๊ทธ๋ž˜์„œ ํƒ์ƒ‰ํ•˜๋Š” ์ˆœ์„œ๋Š” ์ƒ๊ด€์ด ์—†๊ณ , ๋ชจ๋‘ ํƒ์ƒ‰ํ•˜๊ธฐ๋งŒ ํ•˜๋ฉด ๋œ๋‹ค.

๊ทธ๋Ÿฐ๋ฐ ๊ทธ ๊ณผ์ •์—์„œ ์ค‘๋ณต์ด ๋ฐœ์ƒํ•  ์—ฌ์ง€๊ฐ€ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ด๋Ÿฌํ•œ ๋ถ€๋ถ„์„ ์ œ๊ฑฐํ•˜๋ฉด์„œ ์ฐพ์•„์•ผ ํ•œ๋‹ค. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ์ด ๋ฌธ์ œ์—์„œ๋Š” queue๋ง๊ณ  set์„ ์จ์„œ ๊ตฌํ˜„ํ•ด๋„ ๋ฌธ์ œ๊ฐ€ ์—†๋‹ค. queue๋ฅผ ์“ด๋‹ค๋ฉด ์ค‘๋ณต์ œ๊ฑฐ๋ฅผ ํ•ด์•ผํ•˜๋Š”๋ฐ ๊ต‰์žฅํžˆ ๊ท€์ฐฎ๋‹ค.

Code

# BFS๋กœ ์ตœ๋‹จ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์— ๊ตณ์ด queue์ผ ํ•„์š”๊ฐ€ ์—†๋‹ค.
# ์ˆœ์„œ์— ์ƒ๊ด€์—†์ด ์™„์ „ ํƒ์ƒ‰์„ ํ•˜๋Š” ๊ฒƒ์ด ๋ชฉ์ !!
 
import sys
from collections import deque
 
input = sys.stdin.readline
 
r, c = map(int, input().split())
graph = [list(map(str, input().rstrip())) for _ in range(r)]
d = [[1, 0], [0, 1], [-1, 0], [0, -1]]
max_value = 0
 
q = set()
q.add((0, 0, graph[0][0]))
 
while q:
    cy, cx, memory = q.pop()
 
    max_value = max(max_value, len(memory))
 
    for dy, dx in d:
        ny, nx = cy + dy, cx + dx
        if 0 <= ny < r and 0 <= nx < c and graph[ny][nx] not in memory:
            q.add((ny, nx, memory + graph[ny][nx]))
 
print(max_value)

Reference