赞
踩
小明有一块空地,他将这块空地划分为 n 行 m 列的小块,每行和每列的长度都为 1。
小明选了其中的一些小块空地,种上了草,其他小块仍然保持是空地。
这些草长得很快,每个月,草都会向外长出一些,如果一个小块种了草,则它将向自己的上、下、左、右四小块空地扩展,这四小块空地都将变为有草的小块,其中有草的地方为1,空地为0。
请告诉小明,k 个月后空地上哪些地方有草。
tips:队列+模拟
注:我输出的是所有草地的情况,读者可自行修改。相关STL知识详见此处
- #include<iostream>
- #include<vector>
- #include<queue>
- using namespace std;
- ostream &operator << (ostream& out,vector<vector<int>> a) {
- int sum=0;//没长草的土地数
- for(int i=0; i<a.size(); ++i) {
- for(int j=0; j<a[0].size(); ++j) {
- cout<<a[i][j]<<" ";
- if(!a[i][j])
- ++sum;
- }
- cout<<endl;
- }
- cout<<sum<<endl;
- }
- int main() {
- int n,m,k;
- cin>>n>>m>>k;
- vector<vector<int>> a(n,vector<int>(m,0));
- queue<pair<int,int>>q;
- for(int i=0; i<n; ++i)
- for(int j=0; j<m; ++j) {
- cin>>a[i][j];
- if(a[i][j])
- q.push(make_pair(i,j));
- }
- cout<<endl;
- for(int i=0; i<k; ++i) {
- queue<pair<int,int>>temp;
- int flag=0;
- while(!q.empty()) {
- pair<int,int> t = q.front();
- q.pop();
- if(t.first-1>=0&&!a[t.first-1][t.second]) { //上
- a[t.first-1][t.second]=1;
- temp.push(make_pair(t.first-1,t.second));
- flag=1;
- }
- if(t.first+1<n&&!a[t.first+1][t.second]) { //下
- a[t.first+1][t.second]=1;
- temp.push(make_pair(t.first+1,t.second));
- flag=1;
- }
- if(t.second-1>=0&&!a[t.first][t.second-1]) { //左
- a[t.first][t.second-1]=1;
- temp.push(make_pair(t.first,t.second-1));
- flag=1;
- }
- if(t.second+1<=m&&!a[t.first][t.second+1]) { //右
- a[t.first][t.second+1]=1;
- temp.push(make_pair(t.first,t.second+1));
- flag=1;
- }
- }
- if(flag)
- q=temp;
- else break;//如果没有空地可以长草了,提前结束算法
- }
- cout<<a;
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。