例题:
797. 所有可能的路径
模板题
class Solution
{
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph)
{
vector<vector<int>> ans;
queue<vector<int>> q;
vector<int> v{ 0 };
q.push(v);
while (q.empty() == false)
{
v = q.front();
q.pop();
int node = v.back();
if (node == graph.size() - 1)
{
ans.push_back(v);
}
else
{
for (auto i : graph[node])
{
vector<int> temp = v;
temp.push_back(i);
q.push(temp);
}
}
}
return ans;
}
};
102. 二叉树的层序遍历
广度优先搜索在二叉树中的直接应用
class Solution
{
public:
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>> ans; //返回的答案二维数组
if (root == nullptr) //防止树为空
{
return ans;
}
queue<TreeNode*> q;
vector<int> v{ root->val };
ans.push_back(v); //手动存入根节点的值,不然会出错
q.push(root); //将根节点进入队列,作为BFS的“源”
while (q.empty() == false) //外层的while循环是针对二叉树中的每一层,一次循环便是一层
{
vector<int> temp;
int size = q.size();
for (int i = 0; i < size; i++) //内层的for循环是针对一层中所有节点的遍历
{
TreeNode* r = q.front();
q.pop();
if (r->left != nullptr) //先左节点,后右节点,顺序不能错
{
q.push(r->left);
temp.push_back(r->left->val);
}
if (r->right != nullptr)
{
q.push(r->right);
temp.push_back(r->right->val);
}
}
if (temp.empty() == false) //防止答案中出现空的temp
{
ans.push_back(temp);
}
}
return ans;
}
};
练习:
733. 图像渲染
class Solution
{
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color)
{
int oldColor = image[sr][sc];
queue<pair<int, int>> q;
pair<int, int> p(sr, sc);
if (oldColor == color)
{
return image;
}
q.push(p);
image[sr][sc] = color;
while (q.empty() == false)
{
pair<int, int> temp;
p = q.front();
q.pop();
if (p.first > 0
&& image[p.first - 1][p.second] == oldColor)
{
temp.first = p.first - 1;
temp.second = p.second;
image[temp.first][temp.second] = color;
q.push(temp);
}
if (p.first < image.size() - 1
&& image[p.first + 1][p.second] == oldColor)
{
temp.first = p.first + 1;
temp.second = p.second;
image[temp.first][temp.second] = color;
q.push(temp);
}
if (p.second > 0
&& image[p.first][p.second - 1] == oldColor)
{
temp.first = p.first;
temp.second = p.second - 1;
image[temp.first][temp.second] = color;
q.push(temp);
}
if (p.second < image[p.first].size() - 1
&& image[p.first][p.second + 1] == oldColor)
{
temp.first = p.first;
temp.second = p.second + 1;
image[temp.first][temp.second] = color;
q.push(temp);
}
}
return image;
}
};