【BFS】Leetcode---111(E)、515(M)、542(M)

来源:互联网 发布:水资源优化配置 编辑:程序博客网 时间:2024/06/03 22:03

BFS,一般使用先进先出的队列来帮助实现算法,可以有序地保存每层节点


111. Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.


找出最小的深度,使用BFS,第一个叶子结点所在的深度即为所求。

使用队列存下每层的节点

判断当前节点是不是叶子节点,如果不是,则将它的后代存入队列中,如果是则可以返回深度。

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //BFSclass Solution {public:    int minDepth(TreeNode* root) {        if(root == NULL)            return 0;                    queue<TreeNode*> q;        q.push(root);                int depth = 0;        bool flag = false;                while(!q.empty() && flag == false) {                        int n = q.size();            depth++;                        for(int i = 0; i < n; i++) {                TreeNode* cur = q.front();                q.pop();                                if(cur->left == NULL && cur->right == NULL) {                    flag = true;                    break;                }                                    if(cur->left != NULL)                    q.push(cur->left);                if(cur->right != NULL)                    q.push(cur->right);            }        }        return depth;    }};

515. Find Largest Value in Each Tree Row   

You need to find the largest value in each row of a binary tree.

Example:

Input:           1         / \        3   2       / \   \        5   3   9 Output: [1, 3, 9]


 在找出当前层的最大值的同时,保存下一层的节点

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //BFSclass Solution {public:    vector<int> largestValues(TreeNode* root) {        if(root == NULL)            return {};                    queue<TreeNode*> q;        q.push(root);        vector<int> res;                while(!q.empty()) {            int n = q.size();            int maxN = INT_MIN;            //层处理            for(int i = 0; i < n; i++) {                //获取当前层的最大值                TreeNode* cur = q.front();                maxN = max(maxN, cur->val);                                //保存下一层的节点                if(cur->left != NULL) {                    q.push(cur->left);                }                if(cur->right != NULL) {                    q.push(cur->right);                }                q.pop();            }            res.push_back(maxN);        }        return res;    }};


542. 01 Matrix

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1.

Example 1:
Input:

0 0 00 1 00 0 0
Output:
0 0 00 1 00 0 0

Example 2:
Input:

0 0 00 1 01 1 1
Output:
0 0 00 1 01 2 1

Note:

  1. The number of elements of the given matrix will not exceed 10,000.
  2. There are at least one 0 in the given matrix.
  3. The cells are adjacent in only four directions: up, down, left and right.

本来一开始想的是遇到1就对其四周做BFS,但由于其四周的点会有还未确定距离的点,在实现的逻辑上需要绕一下弯(其实也可以实现)

所以就不如从可以确定距离的节点入手,对它四周没有确定距离的节点进行处理(之前没有确定距离的节点若在已知距离的四周,那它在这次搜索中一定会得到确定结果),因为距离是从小到大进行搜索,所以得出的结果符合题意

实现过程需要记录节点是否访问并得出了结果

先确定距离为1的节点,再通过先确定的节点确定其四个方向上未确定的节点的距离,即距离为2;然后再通过距离为2的节点确定其周围节点的距离。。。以此类推


class Solution {public://BFS    vector<pair<int,int>> directions = {{0,-1},{0,1},{-1,0},{1,0}};        vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {        int row = matrix.size();        int col = matrix[0].size();                vector<vector<int>> ans(row ,vector<int>(col,0));                //标记该坐标是否访问并得出结果        vector<vector<bool>> visited(row ,vector<bool>(col, false));                //用于存放已确定距离的1的位置        queue<pair<int, int>> q;                //先确定距离为1的位置并记录下来        for(int i = 0; i < row; i++) {            for(int j = 0; j < col; j++) {                if(matrix[i][j] == 1) {                    for(auto a : directions) {                        int x = i + a.first;                        int y = j + a.second;                        if(x >= 0 && x < row  && y >= 0 && y < col && matrix[x][y] == 0) {                            ans[i][j] = 1;                            visited[i][j] = true;                            q.push(make_pair(i, j));                        }                    }                }            }        }                //从已确定距离的位置进行BFS搜索确定其他节点的距离        while(!q.empty()) {            int i = q.front().first;            int j = q.front().second;            for(auto a : directions) {                int x = i + a.first;                int y = j + a.second;                if(x >= 0 && x < row  && y >= 0 && y < col && matrix[x][y] == 1 && visited[x][y] == false) {                    ans[x][y] = ans[i][j] + 1;                    visited[x][y] = true;                    q.push(make_pair(x, y));                }                            }            q.pop();        }                        return ans;                    }};


原创粉丝点击