Coding Test/백준(Python)

[백준/python] 1987번_알파벳(DFS)

syunze 2024. 2. 21. 17:30

📌문제 유형

DFS, BFS(골드 4)

 

📌문제

 

1987번: 알파벳

세로 $R$칸, 가로 $C$칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 ($1$행 $1$열) 에는 말이 놓여 있다. 말은 상하좌우로 인접한 네 칸 중의

www.acmicpc.net

 

📌나의 문제풀이

- 1%에서 틀려버림,,

r, c = map(int,input().split())

maps = []
for _ in range(r):
    rows = list(map(str, input()))
    maps.append(rows)

def dfs(x,y):
    # print(alpha, visited)
    dx = [0,0,1,-1]
    dy = [1,-1,0,0]

    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]

        if nx >= 0 and nx < r and ny >= 0 and ny < c:
            if visited[nx][ny] == 0:
                visited[nx][ny] = 1

                if maps[nx][ny] in alpha:
                    continue
                else:
                    alpha.append(maps[nx][ny])
                    dfs(nx,ny)
                    # visited[nx][ny] = 0
                    # alpha.pop(len(alpha)-1)

    # dfs(nx+1, ny)
    # dfs(nx, ny+1)
       


visited = [[0 for _ in range(c)] for _ in range(r)]
visited[0][0] = 1
alpha = [maps[0][0]]
dfs(0,0)

print(visited)
print(alpha)
print(len(alpha))

 

📌다른사람의 문제풀이

 - DFS

 

[Python] 백준 1987번 : 알파벳

https://www.acmicpc.net/problem/1987 1987번: 알파벳 세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이 놓여 있다.

codinghejow.tistory.com

 

[BOJ][Python] 백준 1987번 - 알파벳

문제 링크: https://www.acmicpc.net/problem/1987 1987번: 알파벳 세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이

sorryhyeon.tistory.com

import sys
input = sys.stdin.readline

r, c = map(int, input().split())
board = [list(map(lambda x:ord(x)-65, input())) for _ in range(r)]
alpha = [False] * 26
max_ = 1
d = [(1,0), (-1,0), (0,1), (0,-1)]

def DFS(x, y, cnt):
    global max_
    max_ = max(max_, cnt)
    
    for i in range(4):
        nx, ny = x + d[i][0], y + d[i][1]
        
        if 0 <= nx < r and 0 <= ny < c:
            if not alpha[board[nx][ny]]:
                alpha[board[nx][ny]] = True
                DFS(nx,ny,cnt+1)
                alpha[board[nx][ny]] = False
                    
alpha[board[0][0]] = True
DFS(0,0,max_)
print(max_)
r, c = map(int, input().split())
maps = []
for _ in range(r):
    maps.append(list(input()))
ans = 0
alphas = set()
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

def dfs(x, y, count):
    global ans
    ans = max(ans, count)
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if 0 <= nx < r and 0 <= ny < c and not maps[nx][ny] in alphas:
            alphas.add(maps[nx][ny])
            dfs(nx, ny, count+1)
            alphas.remove(maps[nx][ny])
alphas.add(maps[0][0])
dfs(0, 0, 1)
print(ans)

 

📌리뷰

- DFS,BFS는 종료 조건이 없으면 어쨌든 모든 구간을 다 순회한다 -> 위치visited는 필요 없음 

- if문에서 해당 알파벳이 포함되어 있는지 확인 -> 포함되어 있으면 종료, 아니면 진행 

728x90