티스토리 뷰
728x90
반응형
https://www.acmicpc.net/problem/1937
[코드 - Python3]
import sys
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
#상하좌우
dy=(-1,1,0,0)
dx=(0,0,-1,1)
def maxAge(y,x):
global n, MAP, dp
#현위치에 대한 최대수명이 0이 아니라면
if dp[y][x]!=0:
return dp[y][x]
#현위치에 대한 최대수명이 0이다.
dp[y][x]=1 #판다가 살 수 있는 수명은 최소 1일이다.
for i in range(4):
nexty=y+dy[i]
nextx=x+dx[i]
if (nexty>=0 and nexty<n) and (nextx>=0 and nextx<n):
#다음위치의 대나무수가 현위치보다 더 많다면
if MAP[nexty][nextx]>MAP[y][x]:
#현위치의 최대수명= 현위치최대수명, 다음위치 최대수명+1 중 큰값
dp[y][x]=max(dp[y][x], maxAge(nexty, nextx)+1)
return dp[y][x]
if __name__=='__main__':
n=int(input())
#n*n 맵 입력
MAP=[ [*map(int, input().strip().split())] for _ in range(n)]
dp=[ [0]*n for _ in range(n)]
ans=0
for y in range(n):
for x in range(n):
#현위치(y,x)에 놓였을 때 수명을 구한다.
ans=max(ans, maxAge(y,x))
print(ans)
[실패 코드1 - Pypy3 - 시간초과]
- 각 원소별로 최대 수명을 구한다.
- BFS를 이용했다.
- 다음위치의 값(대나무개수)이 현위치의 값보다 크면 큐에 계속 추가하며, 나이를 더한다.
import sys
from collections import deque
input = sys.stdin.readline
q=deque()
#상하좌우
dy=(-1,1,0,0)
dx=(0,0,-1,1)
def bfs(y,x):
global MAP, n
max_age=0
q.append((y,x,1))
visited=[[False]*n for _ in range(n)]
while q:
cury, curx, age=q.popleft()
max_age=max(max_age, age)
for i in range(4):
nexty=cury+dy[i]
nextx=curx+dx[i]
#다음위치가 n행 n열 배열의 원소에 속하는가?
if (nexty>=0 and nexty<n) and (nextx>=0 and nextx<n):
#다음위치가 처음값보다 더 크고, 아직 방문하지 않았는가?
if (MAP[nexty][nextx]>MAP[cury][curx]) and (not visited[nexty][nextx]):
q.append((nexty, nextx, age+1))
return max_age
n=int(input().strip())
MAP=[ [*map(int,input().strip().split())] for _ in range(n)]
dp=[[0]*n for _ in range(n)]
max_age=0
for y in range(n):
for x in range(n):
dp[y][x]=bfs(y,x)
max_age=max(max_age, dp[y][x])
print(max_age)
[참고]
https://yabmoons.tistory.com/154
728x90
반응형
'알고리즘 > BOJ' 카테고리의 다른 글
[BOJ-2583] 영역구하기 (0) | 2020.04.23 |
---|---|
[BOJ-1915] 가장 큰 정사각형 (0) | 2020.04.20 |
[BOJ-1339] 단어수학 (0) | 2020.04.19 |
[BOJ-1987] 알파벳 (0) | 2020.04.19 |
[BOJ-2096] 내려가기 (0) | 2020.04.19 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- MongoDB
- TDD
- RDBMS
- 개발용어
- nestjs
- 나도 할 수 있다
- 바이트디그리
- MySQL
- Mongoose
- typeORM
- gem
- nestjs jest
- IT용어
- 참고
- 한달독서
- Nest.js
- Jekyll
- node.js
- git
- vscode
- TypeScript
- 디지털디톡스
- 습관개선
- jest
- 클린아키텍쳐
- 미완
- 스마트폰중독
- 한달어스
- OS
- 갓생살자
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함