广义优先搜索(BFS)
1.使用BFS的两个主要方案:遍历 或 找出最短路径
2. BFS的伪代码:
【模板一】
/** * Return the length of the shortest path between root and target node. */ int BFS(Node root, Node target) { Queue<Node> queue; // store all nodes which are waiting to be processed int step = 0; // number of steps neeeded from root to current node // initialize add root to queue; // BFS while (queue is not empty) { step = step + 1; // iterate the nodes which are already in the queue int size = queue.size(); for (int i = 0; i < size; ++i) { Node cur = the first node in queue; return step if cur is target; for (Node next : the neighbors of cur) { add next to queue; } remove the first node from queue; } } return -1; // there is no path from root to target }
【模板二】
为了保证代码:不会访问一个结点两次 或 无限循环,可以在【模板一】的基础上添加一个哈希集。
/** * Return the length of the shortest path between root and target node. */ int BFS(Node root, Node target) { Queue<Node> queue; // store all nodes which are waiting to be processed Set<Node> used; // store all the used nodes int step = 0; // number of steps neeeded from root to current node // initialize add root to queue; add root to used; // BFS while (queue is not empty) { step = step + 1; // iterate the nodes which are already in the queue int size = queue.size(); for (int i = 0; i < size; ++i) { Node cur = the first node in queue; return step if cur is target; for (Node next : the neighbors of cur) { if (next is not in used) { add next to queue; add next to used; } } remove the first node from queue; } } return -1; // there is no path from root to target }
补充:不需要使用哈希集的情况:
(1)你完全确定没有循环,例如,在树的遍历中;
(2)你确实希望多次将结点添加到队列中。
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号