Tips
BFS
When to use
- find shortest path: in matrix / from A to B / from one word change to another
Improve
- two end BFS, using two queues, one starting from the beginning, one starting from the end
- e.g., word ladder
DFS
- think about which traversal you want to use
- recursion is easier, iteration needs to use stack
Helper funciton
- use helper function when input or output needs to be different from the original method
- use global variable is easier to update the value
- how to avoid using global variable
- use ReturnType class, if needs to return multiple values
- return result value from the bottom
- Divide and Conquer: bottom-up solution
- divide the problem into small problem that can be implemented on every node
- exit condition
- when node == null, when node is leaf node
- when to return true and when to return false
Improve
- use memorization table / hashmap
- build a signature, and put it into hash set
Visited matrix
- don't forget to label the first element as visited before going into the while loop
- label child elements as visited before adding into the queue
- to avoid using it, you can update the visited elements to a new value