practivceAlgorithm/백준

[백준][Python] 1987 알파뱃

findTheValue 2021. 8. 10. 19:29

완전탐색을 하며 탐색한 값을 배열에 넣어 중복된 값을 탐색하지 않도록 해 최고 값을 저장해주는 방식.

 

import sys
input = sys.stdin.readline
# 좌, 하, 우, 상
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]


def BFS(x, y):
    global answer
    q = set([(x, y, board[x][y])])

    while q:
        x, y, ans = q.pop()

        # 좌우상하 갈 수 있는지 살펴본다
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]

            # index 벗어나지 않는지 체크하고, 새로운 칸이 중복되는 알파벳인지 체크한다
            if ((0 <= nx < R) and (0 <= ny < C)) and (board[nx][ny] not in ans):
                q.add((nx,ny,ans + board[nx][ny]))
                answer = max(answer, len(ans)+1)


R, C = map(int, input().split())
board = [list(input().strip()) for _ in range(R)]

answer = 1
BFS(0, 0)
print(answer)