From dc6562b78a0e3c317bf320a0cbf69cd6ab47f60d Mon Sep 17 00:00:00 2001 From: ByeongKeon Kim Date: Fri, 12 Jul 2024 19:30:48 +0900 Subject: [PATCH] =?UTF-8?q?leetcode.com=20329.=20Longest=20Increasing=20Pa?= =?UTF-8?q?th=20in=20a=20Matrix=20=EB=AC=B8=EC=A0=9C=20=EB=A7=81=ED=81=AC:?= =?UTF-8?q?=20https://leetcode.com/problems/longest-increasing-path-in-a-m?= =?UTF-8?q?atrix/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main.py | 79 ++++++++++--------- 1 file changed, 41 insertions(+), 38 deletions(-) diff --git a/leetcode.com 329. Longest Increasing Path in a Matrix/main.py b/leetcode.com 329. Longest Increasing Path in a Matrix/main.py index 8834c4f..367ea10 100644 --- a/leetcode.com 329. Longest Increasing Path in a Matrix/main.py +++ b/leetcode.com 329. Longest Increasing Path in a Matrix/main.py @@ -1,41 +1,44 @@ from typing import List -class Solution: - def longestIncreasingPath(self, dt: List[List[int]]) -> int: - dp = [[-1 for _ in range(len(dt[0]))] for _ in range(len(dt))] - - for sy in range(len(dt)): - for sx in range(len(dt[0])): - self.dfs(sy, sx, 1, dp, dt) - - answer = 0 - - for sy in range(len(dt)): - for sx in range(len(dt[0])): - answer = max(answer, dp[sy][sx]) - - return answer - - def dfs(self, sy, sx, depth, dp, dt): - if dp[sy][sx] >= depth: - return - dp[sy][sx] = depth - - dyxs = [(-1, 0), (0, 1), (1, 0), (0, -1)] - for dyx in dyxs: - dy, dx = dyx - ty = sy + dy - tx = sx + dx - - if self.is_in(ty, tx, dt): - if dt[sy][sx] < dt[ty][tx]: - if dp[ty][tx] < depth +1: - self.dfs(ty, tx, depth +1, dp, dt) - - - def is_in(self, idx_row, idx_col, map): - if (0 <= idx_row < len(map)) and (0 <= idx_col < len(map[0])): - return True - - return False \ No newline at end of file +class Solution: + def __init__(self): + self.drc = [[-1, 0], [0, 1], [1, 0], [0, -1]] + self.mx_row = 0 + self.mx_col = 0 + + def longestIncreasingPath(self, matrix: List[List[int]]) -> int: + self.mx_row = len(matrix) + self.mx_col = len(matrix[0]) + outdegree: List[List[int]] = [[0 for _ in range(self.mx_col)] for _ in range(self.mx_row)] + leaves = [] + + for r in range(self.mx_row): + for c in range(self.mx_col): + for dr, dc in self.drc: + nr, nc = r + dr, c + dc + if 0 <= nr < self.mx_row and 0 <= nc < self.mx_col: + if matrix[nr][nc] > matrix[r][c]: + outdegree[r][c] += 1 + + if outdegree[r][c] == 0: + leaves.append([r, c]) + + mx = 0 + while len(leaves) > 0: + mx += 1 + newLeaves = [] + + for r, c in leaves: + for dr, dc in self.drc: + nr, nc = r + dr, c + dc + if 0 <= nr < self.mx_row and 0 <= nc < self.mx_col: + if matrix[nr][nc] < matrix[r][c]: + outdegree[nr][nc] -= 1 + + if outdegree[nr][nc] == 0: + newLeaves.append([nr, nc]) + + leaves = newLeaves + + return mx \ No newline at end of file