1987: 알파벳

ewillwin·2023년 7월 2일
0

Problem Solving (BOJ)

목록 보기
99/230

  • 쉬운 backtracking 문제
  • dfs 함수의 인자로 말의 x, y 좌표와 지금까지 지나온 알파벳들을 set 자료형으로 넘겨줌 (in 연산을 할 때, set에선 O(1)임)
  • maxLen을 전역변수로 선언하여 최대값을 구함
import sys

dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]

def dfs(x, y, trace):
    global maxLen
    maxLen = max(len(trace), maxLen)

    for i in range(4):
        nx = x + dx[i]; ny = y + dy[i]
        if 0 <= nx < R and 0 <= ny < C:
            if board[nx][ny] not in trace:
                trace.add(board[nx][ny])
                dfs(nx, ny, trace)
                trace.remove(board[nx][ny])

R, C = map(int, sys.stdin.readline()[:-1].split())
board = []
for r in range(R):
    board.append(list(sys.stdin.readline()[:-1]))

trace = set(board[0][0]); maxLen = 1
dfs(0, 0, trace)
print(maxLen)
profile
Software Engineer @ LG Electronics

0개의 댓글