题解 P1535 【[USACO08MAR]Cow Travelling S】

· · 题解

给自己看的。典型BFS。在BFS中,为了防止重复拓展,需要避免把重复的状态压入队列。这道题的状态是由坐标+时间构成的而不是简单的坐标。所以需要三维。此题又要求我们求出方案数,所以遇到重复状态时直接

有dp那味了。如果不要求方案数的话 $f[xx][yy][step+1]==1$ 的话直接continue。 ``` #include<bits/stdc++.h> using namespace std; const int dx[4]={0,0,1,-1}; const int dy[4]={1,-1,0,0}; int n,m,t,sx,sy,fx,fy; char a[110][110]; int f[110][110][20];//在k时间到达i,j的方案数。坐标+时间作为状态防止重复拓展。 struct node{ int x,y,step; }; queue<node> q; void bfs(int sx,int sy) { q.push((node){sx,sy,0}); f[sx][sy][0]=1; while(q.size()) { node u=q.front(); q.pop(); int x=u.x; int y=u.y; int step=u.step; for(int i=0;i<4;i++) { int xx=x+dx[i]; int yy=y+dy[i]; if(xx<1||yy<1||xx>n||yy>m||a[xx][yy]=='*'||step+1>t) continue; if(f[xx][yy][step+1])//避免重复拓展 { f[xx][yy][step+1]+=f[x][y][step]; continue; } f[xx][yy][step+1]+=f[x][y][step]; q.push((node){xx,yy,step+1}); } } } int main() { cin>>n>>m>>t; for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { cin>>a[i][j]; } } cin>>sx>>sy>>fx>>fy; bfs(sx,sy); cout<<f[fx][fy][t]; return 0; } ```