ν”Όλ“œλ‘œ λŒμ•„κ°€κΈ°
πŸš€ LeetCode 329: Longest Increasing Path in a Matrix (DFS + Memoization) | Easy Explanation
Dev.toDev.to
Backend

Memoization λ„μž…μœΌλ‘œ μ§€μˆ˜ μ‹œκ°„ λ³΅μž‘λ„λ₯Ό O(m*n)으둜 μ΅œμ ν™”ν•œ 경둜 탐색 섀계

πŸš€ LeetCode 329: Longest Increasing Path in a Matrix (DFS + Memoization) | Easy Explanation

swati goyal2026λ…„ 6μ›” 15일8λΆ„intermediate

Context

Matrix λ‚΄ 졜μž₯ 증가 경둜 탐색 μ‹œ λ‹¨μˆœ DFS 기반 Brute Force μ ‘κ·Ό 방식 채택. 동일 경둜의 쀑볡 κ³„μ‚°μœΌλ‘œ μΈν•œ Exponential Time Complexity λ°œμƒ 및 λŒ€κ·œλͺ¨ Matrix 처리 μ‹œ TLE(Time Limit Exceeded) 유발 κ°€λŠ₯μ„± 쑴재.

Technical Solution

  • Overlapping Subproblems 식별을 ν†΅ν•œ Memoization ꡬ쑰 섀계
  • dp[i][j] 배열을 ν™œμš©ν•˜μ—¬ νŠΉμ • μ’Œν‘œμ—μ„œ μ‹œμž‘ν•˜λŠ” 졜μž₯ 경둜 길이λ₯Ό μΊμ‹±ν•˜μ—¬ 쀑볡 계산 제거
  • 4λ°©ν–₯ 탐색을 μœ„ν•œ Direction Array(dx, dy) 기반의 μ •ν˜•ν™”λœ Matrix Traversal νŒ¨ν„΄ 적용
  • matrix[x][y] < matrix[x2][y2] 쑰건을 ν†΅ν•œ μƒνƒœ 전이 μ œμ–΄λ‘œ 사이클 λ°œμƒ κ°€λŠ₯μ„± μ›μ²œ 차단
  • DFS μž¬κ·€ 호좜 κ³Όμ •μ—μ„œ ν•˜μœ„ 문제의 κ²°κ³Όλ₯Ό μƒμœ„ λ…Έλ“œλ‘œ μ „νŒŒν•˜λŠ” Bottom-up λ°©μ‹μ˜ 경둜 길이 ν•©μ‚°
  • Boundary Check λ‘œμ§μ„ ν†΅ν•œ Matrix 인덱슀 Out-of-Bounds μ˜ˆμ™Έ λ°©μ§€

Matrix 탐색 섀계 μ‹œ 쀑볡 μƒνƒœ 쑴재 μ—¬λΆ€λ₯Ό ν™•μΈν•˜μ—¬ Memoization 적용 κ²€ν† . DFS 기반 경둜 탐색 μ‹œ λ°©λ¬Έ 처리 λŒ€μ‹  μƒνƒœ 기반 캐싱을 톡해 μ‹œκ°„ λ³΅μž‘λ„λ₯Ό μ„ ν˜•μ μœΌλ‘œ μ΅œμ ν™”ν•˜λŠ” νŒ¨ν„΄ 적용 κ°€λŠ₯.

원문 읽기