반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 백준 점프
- 백준 점프 파이썬
- 금고털이 파이썬
- MySQL완전삭제
- 도커 컨테이너
- CRUD
- 백준 예산
- 피아노체조 파이썬
- 프로그래머스
- 백준 바이러스
- express mongodb
- 백준 피아노체조
- 파이썬데이터분석라이브러리
- 소프티어 지도자동구축
- express
- 등수매기기 파이썬
- 백준 등수매기기
- 파이썬 평범한배낭
- jenkins
- MongoDB
- 백준 평범한배낭
- 소프티어 장애물인식프로그램
- 1987파이썬
- 지도자동구축 파이썬
- 장애물인식프로그램 파이썬
- 백준 전쟁 파이썬
- 백준알파벳파이썬
- 백준
- 백준 A->B
- 백준 전쟁-전투
Archives
- Today
- Total
바위 뚫는중
[BOJ] 백준 1987. 알파벳 - DFS, 백트래킹 본문
반응형
🥇 알파벳
https://www.acmicpc.net/problem/1987
💡 아이디어
처음엔 BFS로 접근해서 풀이했는데,
최대한 깊게! 어디까지 갈 수 있는지를 보는 것이어서 DFS로 바꿨다.
즉 가능한 모든 경로를 탐색하는 문제다. → DFS로 이동가능한 경로를 탐색하고, Backtracking으로 모든! 경로를 확인한다
🧑🏻💻 풀이
⏰ 시간초과코드: set() 사용
#알파벳 골
r, c = map(int, input().split())
arr = [list(input().rstrip()) for _ in range(r)]
ans = 0
alp = 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 arr[nx][ny] in alp:
alp.add(arr[nx][ny])
dfs(nx, ny, count+1)
alp.remove(arr[nx][ny]) #가장최근 알파벳을 지워줘야함!
alp.add(arr[0][0])
dfs(0,0,1)
print(ans)
✅ 통과 코드: ord 사용
#알파벳 골
r, c = map(int, input().split())
arr = [list(input().rstrip()) for _ in range(r)]
ans = 0
visited=[0]*26 #알파벳은 총 26개
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 visited[ord(arr[nx][ny])-ord('A')]==0:
visited[ord(arr[nx][ny]) - ord('A')] = 1
dfs(nx, ny, count+1)
visited[ord(arr[nx][ny]) - ord('A')] = 0
visited[ord(arr[0][0]) - ord('A')] = 1
dfs(0,0,1)
print(ans)
⚠️
집합의 경우 in 연산자의 대부분의 경우는 시간복잡도가 O(1)이지만, 최악의 경우 O(n)이 될 수도 있다.
visited 리스트를 활용해서 풀이했는데, 리스트는 항상 O(1)의 시간복잡도를 가진다.
최악의 경우를 고려해서,, visited를 사용하는게 낫다 (GPT 참고)
문제 핵심은 DFS를 수행하고, 가장 최근 방문한 알파벳을 삭제하는 것! (백트래킹을 위함) 너무 어려움.
이를 통해 경로상의 알파벳이 중복되지 않고, 최대한 많은 알파벳을 방문할 수 있다.
반응형
'Algorithms > 백준' 카테고리의 다른 글
[BOJ] 백준 1697. 숨바꼭질 - BFS (0) | 2024.06.12 |
---|---|
[Python] 냅색 알고리즘 (Knapsack Problem), 백준 12865. 평범한 배낭 (0) | 2024.02.29 |
[BOJ] 백준 16234. 인구 이동 (파이썬) (1) | 2024.02.29 |
[BOJ] 백준 11727. 2×n 타일링 2 (1) | 2024.02.27 |
[BOJ] 백준 2512. 예산 (1) | 2024.02.15 |