LEARNING JOURNAL

I created this learning journal to practice writting and to help me learn by writting everything down. Source code here

2/21/2024

Pacific Atlantic Water Flow - Depth-First Search

THE PROBLEM

This is the depth-first search approach to the problem. Instead of adding all valid nodes to a queue then pop them out one by one in FIFO order while adding back all the nodes connected to it to the queue like in the breadth-first search, we can use a for loop to examine each valid node, one by one, to go furthest that we can reach for each node, then go back and check another node.

To go furthest, we can use recursive function, in which if we find some neighbor that is valid, we call the recursive function immediately, before checking other neighbor.

Revised by ChatGPT

This is the depth-first search (DFS) approach to the problem. Unlike the breadth-first search (BFS) approach, where we add all valid nodes to a queue and then pop them out one by one in FIFO order while adding back all the connected nodes to the queue, in DFS, we use a for loop to examine each valid node one by one and go as far as we can reach for each node before backtracking to check another node.

To go as far as possible, we use a recursive function. In this function, if we find a valid neighbor, we immediately call the recursive function again for that neighbor before checking the other neighbors. This allow us to explore each path to its fullest before moving on to the next path.