广度优先搜索BFS

广度优先搜索的本质:在一幅图中,从一个起点,走到终点,求出最短路径。

伪代码:

// 计算从起点 start 到终点 target 的最近距离
int BFS(Node start, Node target) 
{
    queue<Node> que; 
    Set<Node> visited; //记录每个点的访问情况

    que.push(start);
    visited.add(start);
    int step = 0; //记录扩散的步数

    while (!que.empty()) 
   {
        int n = que.size();

        /* 将当前队列中的所有节点向四周扩散 */
        for (int i = 0; i < n; i++) 
     {
            Node cur = que.front();
       que.pop();
/* 判断是否到达终点 */ if (cur is target) return step; /* 将 cur 的相邻节点加入队列 */ for (Node x : cur.adj()) if (x not in visited)           { q.push(x); visited.add(x); } } /* 更新步数 */ step++; }    return step; }

 LeetCode-111:二叉树的最小深度

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) 
    {
        if (!root) 
            return 0;

        queue<TreeNode*> que;
        que.push(root);
        int depth = 1;

        while (!que.empty()) 
        {
            int n = que.size();

            /* 将当前队列中的所有节点向四周扩散 */
            for (int i = 0; i < n; ++i) 
            {
                TreeNode* cur = que.front();
                que.pop();

                /* 判断是否到达终点 */
                if (!cur->left && !cur->right) 
                    return depth;

                /* 将 cur 的相邻节点加入队列 */
                if (cur->left)
                    que.push(cur->left);
                if (cur->right) 
                    que.push(cur->right);
            }
            /* 这里增加步数 */
            ++depth;
        }
        return depth;
    }
};

  

原文地址:https://www.cnblogs.com/yongjin-hou/p/15065891.html