https://www.acmicpc.net/problem/1987
1. 시간초과(in사용)
import sys
input = sys.stdin.readline
r, c = map(int,input().split()) # 세로, 가로
arr = [list(input().rstrip()) for _ in range(r)]
visited = []
ans = 0
visited.append(arr[0][0])
def back(i,j,depth):
global ans
ans = max(ans, depth)
for di, dj in [(1,0),(-1,0),(0,-1),(0,1)]:
ni, nj = i+di, j+dj
if 0<=ni<c and 0<=nj<r and arr[nj][ni] not in visited:
visited.append(arr[nj][ni])
back(ni,nj,depth+1)
visited.pop()
back(0,0,0)
print(ans+1)
2. 숫자로 바꿈 + pypy
import sys
input = sys.stdin.readline
r, c = map(int,input().split()) # 세로, 가로
arr = [list(map(lambda x:ord(x)-65, input())) for _ in range(r)]
alpha = [-1] * 26
ans = 1
alpha[arr[0][0]] = 1
def back(i,j,depth):
global ans
if ans < depth:
ans = depth
for di, dj in [(1,0),(-1,0),(0,-1),(0,1)]:
ni, nj = i+di, j+dj
if 0<=ni<c and 0<=nj<r and alpha[arr[nj][ni]] == -1:
alpha[arr[nj][ni]] = 1
back(ni,nj,depth+1)
alpha[arr[nj][ni]] = -1
back(0,0,ans)
print(ans)
보니까 in을 써도 되는데 list가 아닌 set으로 하면 시간이 확 주는건지 시간초과가 안 난다..
'백준' 카테고리의 다른 글
백준 2583. 영역 구하기 (0) | 2025.01.22 |
---|---|
백준 3055. 탈출 (0) | 2025.01.21 |
백준 1525. 퍼즐 (0) | 2025.01.21 |
백준 7576. 토마토 (0) | 2025.01.20 |
프로그래머스 43164. 여행경로 (0) | 2025.01.20 |