class Solution {/广度搜索-队列
public:
int orangesRotting(vector<vector<int>>& grid) {
int m=grid.size(),n=grid[0].size();
int cnt=0;//鲜橘子个数
queue<pair<int,int>>q;
for(int i=0;i<m;++i)
for(int j=0;j<n;++j)
if(grid[i][j]==2)
q.push(make_pair(i,j));
else if(grid[i][j]==1)++cnt;
int res=q.size()?-1:0;//只要有腐烂橘子,比多遍历一遍,res多1
while(q.size()){
int qSize=q.size();
++res;
while(qSize--){
int x=q.front().first,y=q.front().second;
q.pop();
if(x+1<m&&grid[x+1][y]==1){
grid[x+1][y]=2;
q.push(make_pair(x+1,y));
--cnt;
}
if(y+1<n&&grid[x][y+1]==1){
grid[x][y+1]=2;
q.push(make_pair(x,y+1));
--cnt;
}
if(x-1>=0&&grid[x-1][y]==1){
grid[x-1][y]=2;
q.push(make_pair(x-1,y));
--cnt;
}
if(y-1>=0&&grid[x][y-1]==1){
grid[x][y-1]=2;
q.push(make_pair(x,y-1));
--cnt;
}
}
}
return cnt==0?res:-1;
}
};
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 4 <---
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
vector<int>res;
public:
vector<int> rightSideView(TreeNode* root) {
if(!root)return {};
queue<TreeNode*>q;
q.push(root);
while(q.size()){
int qSize=q.size();
while(qSize>=1){
auto temp=q.front();
q.pop();
if(qSize--==1)
res.push_back(temp->val);
if(temp->left)q.push(temp->left);
if(temp->right)q.push(temp->right);
}
}
return res;
}
};