版本比较
5.8
正文
增加 11 行删除 11 行
42 行未改动434445464747484950519 行未改动6162636465656667686944 行未改动11411511611711811811912012112214 行未改动13713813914014114114214314414534 行未改动1801811821831841841851861871884 行未改动19319419519619719719819920020122 行未改动2242252262272282282292302312322 行未改动2352362372382392392402412422432442452462472472482492502516 行未改动25825926026126226226326426526616 行未改动28328428528628728728828929029113 行未改动42 行未改动int main(){ ios::sync_with_stdio(0); cin.tie(0),cout.tie(0);
cin >> n; memset(vis,-1,sizeof(vis)); // 初始化所有格子为未感染 for(int i = 1;i <= n;i ++) {9 行未改动 } } bfs(); // 执行BFS,计算每个格子被感染的时间 cin >> m;
// 统计第m天及之前感染的人数 for(int i = 1;i <= n;i ++) { for(int j = 1;j <= n;j ++)44 行未改动 { node t = q.front(); q.pop(); // 如果当前位置可以直接看到奖杯,返回步数 if(dis[t.x][t.y]) if(dis[t.x][t.y]) { cout << vis[t.x][t.y] << "\n"; f = 1; return ;14 行未改动int main(){ ios::sync_with_stdio(0); cin.tie(0),cout.tie(0);
cin >> n >> m; for(int i = 1;i <= n;i ++) { for(int j = 1;j <= m;j ++)34 行未改动 while(q.size()) q.pop();
if(!f) cout << "Poor Harry\n"; }
return 0;}```### 易错:4 行未改动### 思路:$vis[x][y][dir]$ 表示到达位置 $(x,y)$ 且当前面向方向 $dir$ 时的最小转弯次数。
- 起点:将四个方向都加入队列,转弯次数均为 $0$
每次从队列取出状态,尝试三种转移:
- 直走:沿当前方向走一步,到达新位置,方向不变,转弯次数不变- 左转:方向逆时针转 $90$ 度,位置不变,转弯次数 $+1$22 行未改动 while(q.size()) { node t = q.front(); q.pop();
// 尝试沿着当前方向直走(可以连续走多格) for(int i = 1;i <= 1;i ++) // 实际上只走一步,因为BFS本身会逐步扩展,这里可以改为while循环连续走 { int dx = t.x + d[t.op][0],dy = t.y + d[t.op][1],op = t.op;2 行未改动 if(a[dx][dy] == 'x') continue; // 遇到障碍物,停止该方向 q.push({dx,dy,op}); vis[dx][dy][op] = vis[t.x][t.y][t.op]; // 直走不增加转弯次数 }
// 左转(逆时针90度) int op = (t.op + 1) % 4; if(vis[t.x][t.y][t.op] + 1 < vis[t.x][t.y][op]) // 转弯次数+1,如果更优则更新 { q.push({t.x,t.y,op}); vis[t.x][t.y][op] = vis[t.x][t.y][t.op] + 1; }
// 右转(顺时针90度) op = (t.op + 3) % 4; if(vis[t.x][t.y][t.op] + 1 < vis[t.x][t.y][op]) {6 行未改动int main(){ ios::sync_with_stdio(0); cin.tie(0),cout.tie(0);
cin >> n; memset(vis,0x3f3f3f3f,sizeof(vis)); // 初始化为极大值 for(int i = 1;i <= n;i ++) {16 行未改动 } } } bfs();
// 检查终点是否能到达(任意方向) if(vis[tx][ty][0] == 0x3f3f3f3f) { cout << -1;13 行未改动