2/21/2024
Pacific Atlantic Water Flow - Breadth First Search
This is my breadth-first search approach for this problem.
At first, I thought the queue's length is atmost the number of cells, but it turned out not the case. The reason is that you can add one cell multiple time to the queue. The first time you add is because there is a path to the ocean that going through cell A. Then, you check cell B and it turns out that there is also a path going through that cell to the ocean. So, you might check one cell multiple times. To eliminate the redundancy, I guess, we can use a hash table to keep track of which cells that we already checked.
Another thing that I noticed when implementing the queue is that, it is not necessary empty when this.start === this.end
because it can be full and the end pointer goes around then meets start again. That is why we need to check if both of them point to an empty slot.
Revised by ChatGPT
This is my breadth-first search approach for this problem.
Initially, I thought the queue's length would be atmost the number of cells. However, this is not the case because one cell can be added to the queue multiple times. For example, you might add a cell to the queue because there is a path to the ocean that goes through cell A. Later, you might find that there is also a path to the ocean that goes through cell B, which leads back to cell A. As a result, cell A could be checked multiple times. To eliminate this redundancy, we can use a hash table to keep track of which cells we have already checked.
Another thing I noticed when implementing the queue is that it is not necessarily empty when this.start === this.end
. This is because the queue can be full, and the end pointer might loop around and meet the start pointer again. In this case, both pointers would point to a filled slot, not an empty one. To accurately determine if the queue is empty, we need to check if the slot pointed to by the end pointer is empty (this.arr[this.end][0] === 1
) and if the start and end pointers are at the same position (this.start === this.end
).