题解
该题,内存消耗是比较大的,因为你要开至少接近 40 M的内存空间,但是对于一般机器而言还是撑得住的。
该题单纯的 dfs 是很慢的,且容易算错,所以 bfs 是一个比较好的方法,每隔一分钟所有点就向外扩展一次,然后打个标记,而统计向外扩展的次数可以在每个点预设一个值,代表它是第几次被扩展到的,直至 2020 即可。
#include <iostream> #include <queue> #include <cstring> using namespace std; typedef long long LL; const int N = 10000; LL ans; int maze[N][N]; struct point { int x; int y; int t; }; int row[4] = {-1, 0, 1, 0}, col[4] = {0, 1, 0, -1}; queue <point> q; // 可以用 bfs 来做 int main() { memset(maze, 0, sizeof(maze)); point s; s.x = 2100, s.y = 2100, s.t = 0; q.push(s); s.x = 4120, s.y = 2111, s.t = 0; q.push(s); s.x = 2111, s.y = 2114, s.t = 0; q.push(s); s.x = 4100, s.y = 4100, s.t = 0; q.push(s); // 染色处理 maze[2100][2100] = true, maze[4120][2111] = true; maze[2111][2114] = true, maze[4100][4100] = true; // 总共操作 2020 次 ans = 4; while (!q.empty()) { point a = q.front(); q.pop(); for (int i = 0; i < 4; ++i) { s.x = a.x + row[i]; s.y = a.y + col[i]; s.t = a.t + 1; if (!maze[s.x][s.y] && s.t <= 2020) { maze[s.x][s.y] = true; ++ans; q.push(s); } } } cout << ans << endl; return 0; }
这一题,考场用 dfs 做的,硬是算了好几分钟,但还是算错了,嘤嘤嘤/(ㄒoㄒ)/~~。