문제 링크 : https://www.acmicpc.net/problem/1987
R, C = map(int, input().split())
arr = [list(input()) for _ in range(R)]
# 방향 배열
direct_y = [-1, 1, 0, 0]
direct_x = [0, 0, -1, 1]
ans = 0
cnt = 1
def dfs(y, x):
global ans, cnt
ans = max(ans, cnt)
for i in range(4): # 상하좌우 탐색
dy = y + direct_y[i]
dx = x + direct_x[i]
if 0 <= dy < R and 0 <= dx < C: # 범위 확인
if arr[dy][dx] not in path: # 간 적 없는 알파벳이면
path.append(arr[dy][dx]) # path에 담고
cnt += 1 # count + 1
dfs(dy, dx)
cnt -= 1 # 리턴시 count -1, path에서도 제거
path.remove(arr[dy][dx])
# 좌측 상단에서 시작
path = [arr[0][0]]
dfs(0, 0)
print(ans)
R, C = map(int, input().split())
arr = [list(input()) for _ in range(R)]
direct_y = [-1, 1, 0, 0]
direct_x = [0, 0, -1, 1]
def dfs(ci, cj, cnt):
global ans
ans = max(ans, cnt)
for i in range(4): # 상하좌우 탐색
dy = ci + direct_y[i]
dx = cj + direct_x[i]
if 0 <= dy < R and 0 <= dx < C: # 범위 체크
if visited[ord(arr[dy][dx])] == 0: # 알파벳 중복 체크
visited[ord(arr[dy][dx])] = 1
dfs(dy, dx, cnt+1)
visited[ord(arr[dy][dx])] = 0 # 리턴시 중복체크 해제
ans = 1
visited = [0]*128
visited[ord(arr[0][0])] = 1
dfs(0, 0, 1)
print(ans)
arr[ni][nj]
이 현재 내 시퀀스 안에 담겨 있으면 안됨 not in cv
cv+arr[ni][nj]
가 가본 적 없는 경로여야 함(v배열의 다음 이동할 좌표에 존재하는 시퀀스이면 안됨)not in v[ni][nj]
in
연산자를 사용할 때 list 자료형(O(n)) 보다 set 자료형(O(1))이 더 빠르므로 v 배열을 set 자료형으로 생성from collections import deque
R, C = map(int, input().split())
arr = [list(input()) for _ in range(R)]
def bfs():
q = deque()
# list는 O(N), set은 O(1)
v = [[set() for _ in range(C)] for _ in range(R)]
ans = 1
# q에 초기 데이터 삽입
q.append((0, 0, arr[0][0]))
v[0][0].add(arr[0][0])
while q:
ci, cj, cv = q.popleft() # y좌표, x좌표, 시퀀스
ans = max(ans, len(cv))
for di, dj in ((-1, 0), (1, 0), (0, -1), (0, 1)):
ni, nj = ci+di, cj+dj
# 범위 확인
if 0 <= ni < R and 0 <= nj < C:
# 알파벳이 중복되지 않아야 함
if arr[ni][nj] not in cv:
# 시퀀스가 중복되지 않아야 함
if cv + arr[ni][nj] not in v[ni][nj]:
q.append((ni, nj, cv+arr[ni][nj]))
v[ni][nj].add((cv+arr[ni][nj]))
return ans
print(bfs())
3번 풀이로 최종 제출 하였고, pypy로 실행시 964ms의 시간이 걸렸다.
문어박사 IT편의점 유튜브 - 1987. 알파벳(백준, 파이썬)
https://youtu.be/dR-2lNY77bI