220v
젝무의 개발새발
220v
전체 방문자
오늘
어제
  • 분류 전체보기 (255)
    • AI (35)
      • ML, DL 학습 (30)
      • 논문 리뷰 (4)
      • 실습 및 프로젝트 (1)
    • Algorithm (145)
      • LeetCode (13)
      • 프로그래머스 (35)
      • 백준 (96)
      • 알고리즘, 문법 정리 (1)
    • Mobile, Application (17)
      • Flutter (10)
      • iOS, MacOS (7)
    • BackEnd (7)
      • Flask (1)
      • Node.js (5)
      • Spring, JSP..etc (1)
    • Web - FrontEnd (18)
      • JavaScript, JQuery, HTML, C.. (12)
      • React (6)
    • DataBase (1)
      • MySQL (1)
      • Firebase Firestore (0)
      • Supabase (0)
    • Git (1)
    • 기타 툴 및 오류 해결 (3)
    • 강의 (5)
      • Database (3)
      • 암호학 (2)
      • 알고리즘 (0)
    • 후기와 회고 (2)
    • 블로그 꾸미기 (1)
    • 일상과 이것저것 (20)
      • 맛집 (12)
      • 세상사는일 (4)
      • 도서리뷰 (1)
      • 이런저런 생각들 (잡글) (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Greedy
  • disjoint set
  • 프로그래머스
  • 다익스트라
  • topological sort
  • Lis
  • REACT
  • binary search
  • 위상 정렬
  • Mathematics
  • dfs
  • IMPLEMENT
  • 백준
  • 오블완
  • two pointer
  • Priority Queue
  • dp
  • Prefix Sum
  • brute-Force
  • top-down
  • implementation
  • 구현
  • union-find
  • Minimum Spanning Tree
  • Backtracking
  • BFS
  • simulation
  • bitmasking
  • Dynamic Programming
  • 티스토리챌린지

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
220v

젝무의 개발새발

Algorithm/백준

[백준] 1987. 알파벳 - python

2023. 4. 24. 00:21

[Gold IV]

 

https://www.acmicpc.net/problem/1987

 

1987번: 알파벳

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

www.acmicpc.net

 

풀이 1

이건 그냥.. DFS, Backtracking 이용해서 Recursion으로 풀면 되겠다- 라고 간단하게 생각했다.

 

그런데 가볍게 짠 코드에서 TLE.

import sys
sys.setrecursionlimit(100000)
R, C = map(int, input().split())
board = [list(input()) for _ in range(R)]

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


def dfs(i, j, depth, visited: dict):
    global maxDepth
    if visited.get(board[i][j], 0) == 1 or depth == R*C:
        return

    visited[board[i][j]] = 1
    result.append(depth)

    for k in range(4):
        di = i + dy[k]
        dj = j + dx[k]
        if 0 <= di < R and 0 <= dj < C:
            dfs(di, dj, depth+1, visited)

    if visited.get(board[i][j]):
        visited[board[i][j]] = 0


dfs(0, 0, 1, {})
print(max(result))

 

풀이 2

recursion을 덜 하도록 최적화하여 수정.

 

60~80%? 후반부쯤에서 TLE.

import sys
sys.setrecursionlimit(100000)
R, C = map(int, input().split())
board = [list(input()) for _ in range(R)]

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

visited = {}
maxDepth = 0


def dfs(i, j, depth):
    global maxDepth
    if maxDepth < depth:
        maxDepth = depth

    for k in range(4):
        di = i + dy[k]
        dj = j + dx[k]
        if 0 <= di < R and 0 <= dj < C and visited.get(board[di][dj], 0) != 1:
            visited[board[di][dj]] = 1
            dfs(di, dj, depth+1)
            visited[board[di][dj]] = 0


visited[board[0][0]] = 1
dfs(0, 0, 1)

print(maxDepth)

 

풀이 3

로직 자체는 맞는 것 같은데, python의 특성 때문에 느린 건지 - dictionary를 사용하여 느린 건지 싶어서 visited를 array로 바꿔서 풀었음.

 

AC.

import sys
sys.setrecursionlimit(100000)
R, C = map(int, input().split())
board = [list(input()) for _ in range(R)]

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

visited = [0]*26
maxDepth = 0


def dfs(i, j, depth):
    global maxDepth
    if maxDepth < depth:
        maxDepth = depth

    for k in range(4):
        di = i + dy[k]
        dj = j + dx[k]
        if 0 <= di < R and 0 <= dj < C and visited[ord(board[di][dj])-65] != 1:
            visited[ord(board[di][dj])-65] = 1
            dfs(di, dj, depth+1)
            visited[ord(board[di][dj])-65] = 0


visited[ord(board[0][0])-65] = 1
dfs(0, 0, 1)

print(maxDepth)

 

    'Algorithm/백준' 카테고리의 다른 글
    • [백준] 16173. 점프왕 쩰리 (Small) - 파이썬
    • [백준] 9095. 1, 2, 3 더하기 - 파이썬
    • [백준] 1647. 도시 분할 계획 - python
    • [백준] 12100. 2048 (Easy) - 파이썬
    220v
    220v
    DGU CSE 20 / Apple Developer Academy @ POSTECH 2nd Jr.Learner.

    티스토리툴바