This is still an algorithm note, this time recording the Pacific Atlantic Water Flow Problem on Leetcode last Wednesday (April 27th). The algorithm note is organized based on the official solution, which uses depth-first traversal. Yesterday, I finally encountered a difficult problem (my first reaction: I’m screwed, my streak is going to be broken), but if you pay attention to the details, you can still solve it. For example, <A></A><B></B> is not valid, although it seems valid in HTML, it is because the browser has added <html></html> for us, so it is valid.(English version Translated by GPT-3.5, 返回中文)
When I first started working on this problem, I didn’t have a clue (I found that I would get confused when it comes to depth-first traversal, I just get dizzy when I see it going back and forth), but everything lacks a clue. Once you have a clue, you have half of the problem solved. As a medium-level problem, this problem requires finding the water flow that flows into both the Pacific and Atlantic. We can actually solve it as follows (based on the official solution): first calculate the water flow from the Pacific to the Atlantic, then calculate the water flow from the Atlantic to the Pacific, and finally find the intersection of the two arrays. Break it down as follows:
First, we need to define two arrays to store the water flow from the Pacific to the Atlantic and the water flow from the Atlantic to the Pacific.
Then, build 4 loops to recursively calculate the water flow from the Pacific to the Atlantic horizontally, the water flow from the Pacific to the Atlantic vertically, and the water flow from the Atlantic to the Pacific horizontally and vertically.
Finally, merge the parts of the two arrays that have the same flow direction.
In the recursion, constantly check and recursively determine which direction (up, down, left, right) the “mountain” can flow to the other side, and also determine whether the rocks in these directions are higher. If they are higher, recursively determine where the higher rock can flow to.
Coding Begins
First, define several variables to record the row, column, and height.
1 2
rows = len(matrix) cols = len(matrix[0])
Then, define two arrays to record the water flow from the Pacific to the Atlantic and from the Atlantic to the Pacific.
1 2
pacific = [[False] * cols for _ inrange(rows)] atlantic = [[False] * cols for _ inrange(rows)]
Build four loops to recursively determine the water flow from the Pacific and Atlantic to each other.