题目如下:
输入输出的测试用例如下所示:
测试用例如下:
6 6 2 3 3
37 37 39 41 13 205
37 41 41 203 39 243
37 41 40 131 40 41
91 41 39 198 41 9
189 41 39 40 40 38
37 124 38 167 41 41
这道题采用BFS解决问题,这道题和力扣上岛屿问题很类似。
代码如下:
#include
#include
#include
#include
using namespace std;
void bfs(vector<vector<int>>& grid, vector<vector<bool>>& box, int& nowNum, int nowx, int nowy, int T)
{
vector<int> x = { 0,0,1,-1 };
vector<int> y = { -1,1,0,0 };
int target = grid[nowx][nowy];
queue<pair<int, int>> pos;
pos.push(make_pair(nowx, nowy));
while (!pos.empty()) {
for (int i = 0; i < 4; i++) {
int tempx = pos.front().first + x[i];
int tempy = pos.front().second + y[i];
if (tempx >= 0 && tempy >= 0 && tempx < grid.size() && tempy < grid[0].size() && !box[tempx][tempy]
&& grid[tempx][tempy] >= target - T + 1 && grid[tempx][tempy] <= target + T - 1) {
pos.push(make_pair(tempx, tempy));
box[tempx][tempy] = true;
nowNum++;
}
}
pos.pop();
}
}
int main()
{
int n, m, x, y, t;
int retSum = 0;
cin >> n >> m >> x >> y >> t;
vector<vector<int>> vec(n, vector<int>(m, 0));
vector<vector<bool>> box(n, vector<bool>(m, false));
for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < m; ++j) {
cin >> vec[i][j];
}
}
bfs(vec, box, retSum, y, x, t);
cout << retSum << endl;
system("Pause");
return 0;
}
运行结果如下: