Skip to content

Instantly share code, notes, and snippets.

@mikaelsouza
Created April 4, 2024 01:06
Show Gist options
  • Save mikaelsouza/f0f2ef859afb3312a93515459dfd8371 to your computer and use it in GitHub Desktop.
Save mikaelsouza/f0f2ef859afb3312a93515459dfd8371 to your computer and use it in GitHub Desktop.
class Solution:
def __init__(self):
self.visited = {}
def startWalking(self, heights: List[List[int]], i: int, j: int):
self.visited = {}
up_left = self.walkThroughMatrix(heights, i, j, up_left=True)
self.visited = {}
down_right = self.walkThroughMatrix(heights, i, j, up_left=False)
return up_left and down_right
def walkThroughMatrix(self, heights: List[List[int]], i: int, j: int, prev_height=100_001, up_left=True) -> bool:
if up_left:
if i < 0 or j < 0:
return True
if i >= len(heights) or j >= len(heights[0]):
return False
else:
if i < 0 or j < 0:
return False
if i >= len(heights) or j >= len(heights[0]):
return True
if heights[i][j] > prev_height:
return False
if (i, j) in self.visited:
return False
self.visited[(i, j)] = 1
return self.walkThroughMatrix(heights, i - 1, j, heights[i][j], up_left=up_left) or \
self.walkThroughMatrix(heights, i, j - 1, heights[i][j], up_left=up_left) or \
self.walkThroughMatrix(heights, i + 1, j, heights[i][j], up_left=up_left) or \
self.walkThroughMatrix(heights, i, j + 1, heights[i][j], up_left=up_left)
def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
can = list()
for i in range(len(heights)):
for j in range(len(heights[0])):
if self.startWalking(heights, i, j):
can.append([i, j])
return can
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment