# Implementation of leetcode breadth first search code framework

Keywords: Algorithm leetcode

# Implementation of leetcode BFS code framework

Learning experience:

1. There is such a sentence in the algorithm sketch. The operation of binary tree can derive a lot of algorithm ideas. More and more questions are brushed, and more and more experience will be gained
2. There are also two forms of binary tree traversal, DFS and BFS. DFS includes three forms of traversal before, during and after sequence, and BFS only has hierarchical traversal,
3. Hierarchical traversal is divided into types. Different data structures are used to derive different traversal sequences. You can do 32 questions in sword finger offer to specific operation queues
4. There is also a certain correlation between DFS and BFS target operations, but that is to add the pending data to the container, and then get the corresponding data from the container for processing. BFS is the queue and DFS is the stack
5. Another way of thinking, if this container is changed arbitrarily, there will be various search algorithms. If it is placed in a heap, a minimum spanning tree will be generated, and if it is placed in a random container, it will be more fun, and so on

DFS code framework idea:

1. Create a core data structure queue and a visit set to avoid going back many times
2. Add the starting point to the queue and set visit to true
3. Enter the queue, take out the starting point, spread the path, and judge when the end point is reached,
4. Add the queue adjacent to the node to the queue and update the required extreme value

The code framework is as follows:

```    int BFS(Node start,Node target){
Queue<node> queue;//Core data structure
Set<Node> visited;//Avoid going back

int step = 0;//Record the number of diffusion steps
while(q not empty){
int sz = queue.size();
//Spread all nodes in the current queue around
for (int i = 0; i < sz; i++) {
Node cur = queue.poll();
//The judgment time has reached the end
if (cur is target){
return step;
}
if (x not in visited){
queue.offer(x);
}
}
}
//Focus and update the steps here
step++;
}
}
```

leetcode question 111 minimum depth of binary tree

Experience:

1. Before doing this problem, I did the problem of finding the maximum depth of binary tree. I thought in the same way, but the error did not take into account that the left or right child nodes of the root node are null

2. The core framework of bfs is not difficult to understand, which is to abstract some problems into a graph, start from one point and spread around,

3. The main difference between BFS and DFS is that the relative path found by BFS must be the shortest, but the cost is that the spatial complexity is much larger than that of DFS,

1. Why can BFS find the shortest distance? Can't DFS?

First, look at the logic of BFS. Every time depth is added, all nodes in the queue will take a step forward, which ensures that the number of steps taken is the least when reaching the destination for the first time.

Can DFS not find the shortest path? In fact, it is OK, but relatively speaking, the time complexity will be much higher. DFS actually walks through all paths by means of recursive stack records. It must be necessary to compare all tree branches in the binary tree with the search network to find out how long the shortest path is

With the help of queues, BFS can go one step at a time and go hand in hand. It can find the shortest distance without traversing the whole tree

```lass Solution {
public int minDepth(TreeNode root) {
//I'm just bored. Why can't I do these problems? I'm really angry!
//Binary tree is actually a very simple data structure. Breadth first is that the data structures of applications are different, and depth first is the queue of applications
if (root == null){
return 0;
}
queue.offer(root);
int depth = 1;
while(!queue.isEmpty()){
int sz = queue.size();
for(int i = 0;i < sz;i++){
TreeNode curnode = queue.poll();
if (curnode.right == null && curnode.left == null){
return depth;
}
if (curnode.left != null){
queue.offer(curnode.left);
}
if (curnode.right != null){
queue.offer(curnode.right);
}
}
depth++;
}
return depth;
}

}
```
###### leetcode question 752, open the turntable lock

Idea:

```1. The difficulty of this problem is that it cannot appear deadends，How to calculate the shortest path,
2. We don't care about all the restrictions, no matter deadend and target If you were asked to design an algorithm and enumerate all password combinations, what would you do
3. If you only need to turn the lock, there are several possibilities. There are four positions in total. Each position can turn up or down, that is, there are eight possibilities,
4. Starting from 0000, you can cite 1000 9000 0100 0900 in one turn ...These eight kinds of passwords, and then use the password as the basis. After each password is turned, list all the possibilities
5. If you think about it carefully, you can abstract out a picture. Each node has eight adjacent nodes, which allows you to find the shortest distance. Isn't that typical BFS Then the framework can be used in the factory
```
```class Solution {
public int openLock(String[] deadends, String target) {
//Store the death password we need to skip
}
//      Check the memo to see if we have added this string
HashSet<String> memo = new HashSet<>();
//Using the data structure of queue to build a bfs algorithm framework
queue.offer("0000");
//Breadth first traversal search from the starting point
int step = 0;
while (!queue.isEmpty()) {
int sz = queue.size();
//Spread all nodes in the current queue around
for (int i = 0; i < sz; i++) {
String curStr = queue.poll();
//The judgment passed our death code
continue;
}
//Judge when you have reached the end
if (curStr.equals(target)) {
return step;
}
//Starting from the traversed node, add the queue
for (int j = 0; j < 4; j++) {
String up = turnUp(curStr, j);
if(!memo.contains(up)){
queue.offer(up);
}

String down = turnDown(curStr, j);

if (!memo.contains(down)) {
queue.offer(down);
}
}
}
step++;
}

return -1;
}
//First write the method of turning upward
public String turnUp(String str,int j){
char[] chars = str.toCharArray();
if (chars[j] == '9'){
chars[j] = '0';
}else{
chars[j] += 1;
}
return new String(chars);
}

public String turnDown(String str,int j){
char[] chars = str.toCharArray();
if (chars[j] == '0'){
chars[j] = '9';
}else{
chars[j] -= 1;
}
return new String(chars);
}
}
```

Posted by michaelphipps on Fri, 05 Nov 2021 16:01:57 -0700