带状态的bfs
用一个数(ks)来表示状态-当前连续穿越的障碍数;
step表示当前走过的步数;
visit数组也加一个状态;
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <queue> 5 using namespace std; 6 7 const int maxn = 30 ; 8 9 struct node { 10 int x,y; 11 int step; 12 int ks; 13 void init (int nx,int ny,int nstep,int nks){ 14 x=nx;y=ny;step=nstep;ks=nks; 15 } 16 }; 17 18 int n,m,k; 19 int map[maxn][maxn],visit[maxn][maxn][maxn]; 20 int dir[4][2]={1,0,-1,0,0,1,0,-1}; 21 22 int bfs (){ 23 queue<node> q; 24 while (!q.empty ()) 25 q.pop (); 26 node a,b; 27 a.init (1,1,0,0); 28 q.push (a); 29 while (!q.empty ()){ 30 a=q.front (); 31 q.pop (); 32 33 int xx,yy,sstep,kss; 34 for (int i=0;i<4;i++){ 35 xx=a.x;yy=a.y;sstep=a.step;kss=a.ks; 36 xx+=dir[i][0]; 37 yy+=dir[i][1]; 38 sstep+=1; 39 if (xx<1||xx>n||yy<1||yy>m) 40 continue ; 41 if (map[xx][yy]) 42 kss++; 43 else kss=0; 44 if (kss>k) 45 continue ; 46 if (visit[kss][xx][yy]) 47 continue ; 48 if (xx==n&&yy==m) 49 return sstep ; 50 b.init (xx,yy,sstep,kss); 51 q.push (b); 52 visit[kss][xx][yy]=1; 53 } 54 } 55 return -1; 56 } 57 58 int main (){ 59 int t; 60 cin>>t; 61 while (t--){ 62 cin>>n>>m>>k; 63 if (n==m&&n==1){ 64 cout<<0<<"error"<<endl; 65 continue ; 66 } 67 memset (visit,0,sizeof visit); 68 for (int i=1;i<=n;i++) 69 for (int j=1;j<=m;j++) 70 cin>>map[i][j]; 71 int ans=bfs (); 72 cout<<ans<<endl; 73 } 74 return 0; 75 }
UVA 1600 Patrol Robot,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/gfc-g/p/3860953.html