Skip to main content

Leetcode 417. Pacific Atlantic Water Flow. Python (Dfs Graph)

417Pacific Atlantic Water Flow


There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.

The island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).

The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.

Return 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.

 

Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
Explanation: The following cells can flow to the Pacific and Atlantic oceans, as shown below:
[0,4]: [0,4] -> Pacific Ocean 
       [0,4] -> Atlantic Ocean
[1,3]: [1,3] -> [0,3] -> Pacific Ocean 
       [1,3] -> [1,4] -> Atlantic Ocean
[1,4]: [1,4] -> [1,3] -> [0,3] -> Pacific Ocean 
       [1,4] -> Atlantic Ocean
[2,2]: [2,2] -> [1,2] -> [0,2] -> Pacific Ocean 
       [2,2] -> [2,3] -> [2,4] -> Atlantic Ocean
[3,0]: [3,0] -> Pacific Ocean 
       [3,0] -> [4,0] -> Atlantic Ocean
[3,1]: [3,1] -> [3,0] -> Pacific Ocean 
       [3,1] -> [4,1] -> Atlantic Ocean
[4,0]: [4,0] -> Pacific Ocean 
       [4,0] -> Atlantic Ocean
Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.

 

Constraints:

  • m == heights.length
  • n == heights[r].length
  • 1 <= m, n <= 200
  • 0 <= heights[r][c] <= 105

 

Solution :

class Solution:
    def pacificAtlantic(self, h: List[List[int]]) -> List[List[int]]:
        
        ROWS, COLS = len(h), len(h[0])
        p, a = set(), set()
        ans = []
        
        def dfs(r, c, vs, prev_h):
            
            if ((r,c) in vs or
               r < 0 or c < 0 or r == ROWS or c == COLS or
               h[r][c] < prev_h):
                return
            
            vs.add((r,c))
            
            dfs(r+1, c, vs, h[r][c])
            dfs(r-1, c, vs, h[r][c])
            dfs(r, c+1, vs, h[r][c])
            dfs(r, c-1, vs, h[r][c])
            
        for c in range(COLS):
                dfs(0, c, p, h[0][c])
                dfs(ROWS-1, c, a, h[ROWS-1][c])
                
        for r in range(ROWS):
                dfs(r, 0, p, h[r][0])
                dfs(r, COLS-1, a, h[r][COLS-1])
                
            
        for r in range(ROWS):
                for c in range(COLS):
                    if (r,c) in p and (r,c) in a:
                        ans.append([r,c])
                        
        return ans


Explaination :





Comments

Popular posts from this blog

Leetcode 424. Longest Repeating Character Replacement. Python (Sliding Window)

  424 .  Longest Repeating Character Replacement You are given a string  s  and an integer  k . You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most  k  times. Return  the length of the longest substring containing the same letter you can get after performing the above operations .   Example 1: Input: s = "ABAB", k = 2 Output: 4 Explanation: Replace the two 'A's with two 'B's or vice versa. Example 2: Input: s = "AABABBA", k = 1 Output: 4 Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA". The substring "BBBB" has the longest repeating letters, which is 4.   Constraints: 1 <= s.length <= 10 5 s  consists of only uppercase English letters. 0 <= k <= s.length Solution :  class Solution: def characterReplacement(self, s: str, k: int) -> int: hm = {} ans = 0

Leetcode 371. Sum of Two Integers. C++ / Java

371 .  Sum of Two Integers   Given two integers  a  and  b , return  the sum of the two integers without using the operators   +   and   - .   Example 1: Input: a = 1, b = 2 Output: 3 Example 2: Input: a = 2, b = 3 Output: 5   Constraints: -1000 <= a, b <= 1000 Solution :  C++ : class Solution { public: int getSum(int a, int b) { if (b==0) return a; int sum = a ^ b; int cr = (unsigned int) (a & b) << 1; return getSum(sum, cr); } }; Java :  class Solution { public int getSum(int a, int b) { while(b != 0){ int tmp = (a & b) << 1; a = a ^ b; b = tmp; } return a; } } Explaination :

Leetcode 242. Valid Anagram. Python (3 Ways)

  242 .  Valid Anagram Given two strings  s  and  t , return  true   if   t   is an anagram of   s , and   false   otherwise . An  Anagram  is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.   Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false   Constraints: 1 <= s.length, t.length <= 5 * 10 4 s  and  t  consist of lowercase English letters.   Follow up:  What if the inputs contain Unicode characters? How would you adapt your solution to such a case? class Solution: def isAnagram(self, s: str, t: str) -> bool: return sorted(s) == sorted(t) # return Counter(s) == Counter(t) # cs, ct = {}, {} # if len(s) != len(t): # return False # for i in range(len(s)): # cs[s[i]] = 1 + cs.get(s[i], 0) #