Personal understanding
BFS is one of the most simple graph search algorithm, by traversing the entire map until it finds the target node;
From the perspective of the algorithm of view, because all the bytes expand the node points obtained will be stored in a FIFO data structure is traversed nodes stored in a container (usually a SET), to prevent duplicate search
Diagram
As shown, we want to get the shortest path from S to node E, the use of BFS, how to deal with? ?
The main idea is: starts from node S to store all of its child nodes adjacent to a queue, then the distance to the node labeled these initial vertex S is 1;
The FIFO queue then specified, a queue, determining whether the target node; if not near the child node, the enqueue dequeue node until the queue is empty
Fake code
int BFS(Node root, Node target) {
Queue<Node> queue;
Set <Node> set; // to store visited node
queue.add(root);
set.add(root);
int instance = 0; // identifies the root node to the target node distance
while(queue is not empty) {
instance++;
int queueSize;
for (index = 0; index < queueSize; index++) {
node = queue.remove (); // get the root queue
if (node is target node) {
return instance;
}
add node next nodes in queue; // close all the nodes of a child node into the queue
}
}
return -1;
}
Stay button corresponding to the exercises
https://leetcode-cn.com/problems/open-the-lock/
https://leetcode-cn.com/problems/perfect-squares/
Personal point of view --- not like do not spray, please correct me, common learning and common progress
Difficulties such algorithms question is how to disassemble a given topic, and applied to the BFS; no shortcuts, BFS requires a deep understanding of thought, and then engage in active practice it.