题目:
[音源所在行,列,噪声值]的xing形式记录在二维数组中。
- 噪音沿相邻的八个方向传播,在传播的过程中,噪音值(单位为分贝)逐级递减1分贝,直至削弱到1(即噪音源覆盖区域边缘噪音分贝为1);
- 若同一格被多个噪音覆盖,监测结果不叠加,仅保留较大的噪音值(噪音源所在的格也可能被其他噪音源的噪音传播覆盖)。
所在有噪音源且持续传播情况稳定后,请监测每格噪音分贝数并返回他们的总和。注意:
- 除噪音源外的所有格初始值为0分贝
- 不考虑墙面反射
示列:
输入:n =5, m=6, noise=[[3,4,3],[1,1,4]]
输出:63
解释:
3 3 3 2 1 0
3 4 3 2 1 1
3 3 3 2 2 2
2 2 2 2 3 2
1 1 1 2 2 2
#include<vector>
#include<iostream>
using namespace::std;
class Solution {
public:
int SpreadNoise(int n, int m,vector<vector<int> >& noise)
{
vector<vector<int>> feild(n, vector<int>(m));//n行 m列
for(int i = 0; i < noise.size(); i++)
{
SpreadNoiseProc(feild, noise[i]);
}
int sum = 0;
for(int i = 0; i < feild.size(); i++)
{
for(int j = 0; j < feild[i].size(); j++)
{
sum += feild[i][j];
cout<<feild[i][j]<<' ';
}
cout<<'\n';
}
return sum;
}
void SpreadNoiseProc(vector<vector<int>> &feild, const vector<int> &one_noise)
{
int x = one_noise[0];
int y = one_noise[1];
int n = feild.size() ;//行
int m = feild[0].size();//列
feild[x][y] = one_noise[2];
Spread(feild, x, y);
int max_far = max(max(n-x-1, x), max(m-y-1, y));
max_far = min(max_far, one_noise[2]);
cout << max_far<<endl;
for(int i = 1; i <= max_far; i++)
{
for(int j = y + 1 - i; j < y + i ; j++)
{
if(x-i >=0 && j >= 0 && j < m)
Spread(feild, x - i, j);
if(x+i < n && j >= 0 && j < m)
Spread(feild, x + i, j);
}
for(int j = x -i; j <= x + i; j++)
{
if(y-i >= 0 && j >= 0 && j < n)
Spread(feild, j, y - i);
if(y+i < m && j >= 0 && j < n)
Spread(feild, j, y + i);
}
}
}
void Spread(vector<vector<int>> &feild, int x, int y)
{
int n = feild.size();
int m = feild[0].size();
if(x-1 >= 0)
{
feild[x-1][y] = max(feild[x-1][y], feild[x][y] - 1);
if(y-1 >= 0)
{
feild[x-1][y-1] = max(feild[x-1][y-1], feild[x][y] - 1);
feild[x][y-1] = max(feild[x][y-1], feild[x][y] - 1);
}
if(y+1 < m)
{
feild[x-1][y+1] = max(feild[x-1][y+1], feild[x][y] - 1);
feild[x][y+1] = max(feild[x][y+1], feild[x][y] - 1);
}
}
if(x+1 < n)
{
feild[x+1][y] = max(feild[x+1][y], feild[x][y] - 1);
if(y-1 >=0)
{
feild[x+1][y-1] = max(feild[x+1][y-1], feild[x][y] - 1);
}
if(y+1 < m)
{
feild[x+1][y+1] = max(feild[x+1][y+1], feild[x][y] - 1);
}
}
}
};
int main(int argc, char * argv[])
{
int sum = 0;
vector<int> noise_a = {3, 4, 3};
vector<int> noise_b = {1, 1, 4};
vector<vector<int> > noise = {noise_a, noise_b};
Solution abj;
sum = abj.SpreadNoise(5, 6, noise);
cout<<sum<<endl;
return 0;
}