一个出水管每过一分钟就像外四个方向灌溉(上下左右)灌溉一个单位的土地,请问t个水管k分钟后能灌溉多少个单位的土地
#include <iostream>
using namespace std;
#define maxn 101
#include <cstring>
int dir[4][2] = {{0, 1},
{0, -1},
{1, 0},
{-1, 0}
};
int main() {
int n, m;
cin >> n >> m;
int t, x, y;
int hash[maxn][maxn];//定义一个哈希二维数组
int q[maxn * maxn]; //定义一个队列
int front = 0, rear = 0; //初始化头尾指针
memset(hash, -1, sizeof (hash)); //将哈希数组中的元素全部初始化为-1,代表还没有被灌溉
cin >> t;
for (int i = 1; i <= t; i++) {
cin >> x >> y;//水管的初始位置
if (-1 == hash[x][y]) {
hash[x][y] = 0; //这里说明这个点被灌溉到的时间是第0分钟,将灌溉点压入队列
q[rear++] = x * 1000 + y; //rear++表示入队,将位置信息合并成一个数据后入队,为什么*1000,因为xy最大为100
}
}
int k;
cin >> k;//第几分钟停止灌溉
while (front < rear) { //队列不为空的意思
int v = q[front++];//出队第一个元素
int x = v / 1000;//取出x,y值
int y = v % 1000;
if (hash[x][y] == k) { //
continue;
}
for (int i = 0; i < 4; i++) { //遍历四个方向计算各点的xy值
int tx = x + dir[i][0];//0列代表行
int ty = y + dir[i][1];//1列代表列
if (tx > n || tx < 1 || ty > m || ty < 1) {//当位置点越界直接跳出
continue;
}
if (hash[tx][ty] != -1) {//不等于-1说明这个点在之前就已经被灌溉
continue;
}
hash[tx][ty] = hash[x][y] + 1;//tx ty被灌溉到的时间一定是x y的下一分钟,所以加一
q[rear++] = tx * 1000 + ty;//把即将被灌溉点压入队列
}
}
int ans = 0;
for (int i = 0; i <= n; i++) {//遍历将灌溉到的格子累加起来
for (int j = 0; j <= m; j++) {
if (hash[i][j] != -1) {
ans++;
}
}
}
cout << ans;
return 0;
}