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
- LongestIncreasingPathinaMatrix
- IOS개발기
- 백준알고리즘
- 329번
- 리트코드
- 홀수홀릭호석
- 15684
- iOS개발
- leetcode329
- IOS입문
- 사다리조작
- 백죽
- dataframe
- 백준문제
- 백준
- IOS도전기
- 2212
- 크게만들기
- iOS앱개발
- 프로그래머스
- 329
- leetcode
- 센서
- stack문제
- 2812번
- IOS도전
- 20164번
- 릿코드
- 2212번
- BOJ
Archives
- Today
- Total
알고리즘 풀어주는 블로그
LEETCODE 329 : Longest Increasing Path in a Matrix - python 본문
Q. 문제
ttps://leetcode.com/problems/longest-increasing-path-in-a-matrix/
Longest Increasing Path in a Matrix - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
A. 풀이
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
result = 0
visit = [[1]*len(matrix[0]) for _ in range(len(matrix))]
def dfs(x, y, n):
ans = n
for d in range(4):
tx = x + dx[d]
ty = y + dy[d]
if tx < 0 or ty < 0 or tx >= len(matrix) or ty >= len(matrix[0]):
continue
if matrix[tx][ty] > matrix[x][y] and visit[tx][ty] <= visit[x][y] + 1:
visit[tx][ty] = visit[x][y] + 1
ans = max(dfs(tx, ty, n + 1), ans)
return ans
for i in range(len(matrix)):
for j in range(len(matrix[0])):
result = max(dfs(i, j, 1), result)
return result
가장 긴 증가 길이 찾기
일종의 동적 계획법인데 루트를 추적하는게 dfs의 재귀를 이용해서 풀었다.
1) visit 배열에 해당 위치에서 가질 수 있는 길이를 저장
2) 더 작은 방문일 경우에는 검사하지 않도록 제외시킴 -> 시간 단축
'알고리즘 문제 > leetcode' 카테고리의 다른 글
leetcode 329 : Longest Increasing Path in a Matrix - python (0) | 2021.05.17 |
---|