每日刷题(117)
扩散
题目描述
本题为填空题,只需要算出结果后,在代码中使用输出语句将所填结果输出即可。
小蓝在一张无限大的特殊画布上作画。
这张画布可以看成一个方格图,每个格子可以用一个二维的整数坐标表示。
曼哈顿距离法分析
C++题解
#include<bits/stdc++.h>
using namespace std;
int main()
{
int ans = 0;
for(int x = 0 - 2020; x <= 2020 + 2020; x++)
{
for(int y = 0 - 2020; y <= 2000 + 2020; y++)
{
if(abs(x - 0) + abs(y - 0) <= 2020 || abs(x - 2020) + abs(y - 11) <= 2020 || abs(x - 11) + abs(y - 14) <= 2020 || abs(x - 2000) + abs(y - 2000) <= 2020)
{
ans++;
}
}
}
cout << ans << endl;
return 0;
}
所以答案就是20312088
BFS版
#include<bits/stdc++.h>
using namespace std;
const int N = 7e3 + 10;
struct node{
int x, y, cnt;
};
int nex[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
const int B = 2020;
int b[N][N];
int bfs()
{
queue<node> que;
int cnt = 4;
//对初始的四个点的坐标都加2020,防止之后bfs后出现坐标为负数的情况
//因为b数组只能存储正数序号的坐标的访问情况
que.push(node{0 + B, 0 + B, 0});
que.push(node{2020 + B, 11 + B, 0});
que.push(node{2000 + B, 2000 + B, 0});
que.push(node{11 + B, 14 + B, 0});
b[0 + B][0 + B] = 1;
b[2020 + B][11 + B] = 1;
b[2000 + B][2000 + B] = 1;
b[11 + B][14 + B] = 1;
while(!que.empty())
{
node u = que.front();
que.pop();
if(u.cnt == 2020)
{
continue;
}
for(int i = 0; i < 4; i++)
{
int tx = u.x + nex[i][0], ty = u.y + nex[i][1];
if(b[tx][ty])
{
continue;
}
cnt++;
b[tx][ty] = 1;
que.push(node{tx, ty, u.cnt + 1});
}
}
return cnt;
}
int main()
{
cout << bfs() << endl;
return 0;
}