题解 AT2487 【チーズ (Cheese)】
蒟蒻又来发题解了...
人生自古谁无死,留篇题解帮萌新!
一、思路
这道题目我们可以用BFS解决。
因为必须要先走数字小的,再走数字大的,所以我们做多遍BFS,每一遍BFS从当前数字走到比他大一的数字,将答案加上这条路径。在输入时记录每个数字的坐标。
二、萌新请注意
如果没学过BFS,可以去这里学习BFS,入门后可以自己找题练习一下,然后再来做这题。
三、代码
谔谔,竟然没什么好说的了。那就上代码吧。
#include<bits/stdc++.h> using namespace std; struct ttt { int x; int y; }; struct st { int x; int y; int s; }; ttt a[10]; int h,w; int n; char c[1001][1001]; int dir[4][2]={1,0,0,1,-1,0,0,-1}; bool vis[1001][1001]; int bfs(int sx,int sy,int ex,int ey) { queue<st>q; st now; now.x=sx; now.y=sy; now.s=0; q.push(now); while(!q.empty()) { st t; t=q.front(); q.pop(); if(t.x==ex&&t.y==ey) { return t.s; } int i; for(i=0;i<4;i++) { now.x=t.x+dir[i][0]; now.y=t.y+dir[i][1]; now.s=t.s+1; if(c[now.x][now.y]!='X'&&!vis[now.x][now.y]&&now.x>0&&now.y>0&&now.x<=h&&now.y<=w) { vis[now.x][now.y]=true; q.push(now); } } } } int main() { int i,j; cin>>h>>w>>n; for(i=1;i<=h;i++) { for(j=1;j<=w;j++) { cin>>c[i][j]; if(c[i][j]>='1'&&c[i][j]<='9') { a[c[i][j]-'0'].x=i; a[c[i][j]-'0'].y=j; } if(c[i][j]=='S') { a[0].x=i; a[0].y=j; } } } int sum; sum=0; for(i=0;i<n;i++) { int sx,sy,ex,ey; sx=a[i].x; sy=a[i].y; ex=a[i+1].x; ey=a[i+1].y; memset(vis,false,sizeof(vis)); sum+=bfs(sx,sy,ex,ey); } cout<<sum<<endl; return 0; }
不要妄图追上西坠的太阳,而是要在黎明前就等着它!