https://www.acmicpc.net/problem/1987
1987번: 알파벳
세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이 놓여 있다. 말은 상하좌우로 인접한 네 칸 중의 한 칸으
www.acmicpc.net
<내 코드>
- 큐를 set을 활용해서 중복을 방지하였다.
- 현재 알파벳을 기록해주고 현재 알파벳이 이동할 곳에 아직 없을때만 이동해서 지난 알파벳은 방문하지 않는다.
import sys
r,c = map(int, input().split())
graph = []
for _ in range(r):
graph.append(list(input()))
dx = [0,0,1,-1]
dy = [1,-1,0,0]
def bfs(x,y):
global answer
queue = set([(x,y,graph[x][y])])
while queue:
x,y,alphas = queue.pop()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0<=nx<r and 0<=ny<c and graph[nx][ny] not in alphas:
queue.add((nx,ny,alphas+graph[nx][ny]))
answer = max(answer, len(alphas)+1)
answer = 1
bfs(0,0)
print(answer)
'알고리즘 > DFS, BFS' 카테고리의 다른 글
[백준-실버1] 1303번 전쟁-전투(DFS, 파이썬) (0) | 2022.01.20 |
---|---|
[백준-실버2] 3184번 양(DFS, 파이썬) (0) | 2022.01.19 |
[백준-실버1] 1697 숨바꼭질(파이썬, BFS) (0) | 2022.01.13 |
[백준-실버1] 7576 토마토(파이썬 , BFS) (0) | 2022.01.13 |
[프로그래머스 - Level 2] 타겟넘버(파이썬) (0) | 2022.01.11 |