题意:
网格中有一些障碍物,求从起点到终点最小步数。-500≤坐标≤500
题解:
bfs。所有坐标均加上500,就可以只考虑第一象限了。
代码:
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <queue> 5 #define inc(i,j,k) for(int i=j;i<=k;i++) 6 #define maxn 1010 7 using namespace std; 8 9 inline int read(){ 10 char ch=getchar(); int f=1,x=0; 11 while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();} 12 while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar(); 13 return f*x; 14 } 15 int dis[maxn][maxn],x,y,n; bool bad[maxn][maxn]; queue<pair<int,int> >q; 16 int main(){ 17 x=read()+500; y=read()+500; n=read(); inc(i,1,n){int x=read()+500,y=read()+500; bad[x][y]=1;} 18 q.push(make_pair(500,500)); memset(dis,-1,sizeof(dis)); dis[500][500]=0; 19 while(!q.empty()){ 20 int xx=q.front().first,yy=q.front().second; q.pop(); 21 if(xx>-1000&&!bad[xx-1][yy]&&dis[xx-1][yy]==-1){ 22 q.push(make_pair(xx-1,yy)); dis[xx-1][yy]=dis[xx][yy]+1; 23 if(xx-1==x&&yy==y){printf("%d",dis[xx-1][yy]); break;} 24 } 25 if(xx<1000&&!bad[xx+1][yy]&&dis[xx+1][yy]==-1){ 26 q.push(make_pair(xx+1,yy)); dis[xx+1][yy]=dis[xx][yy]+1; 27 if(xx+1==x&&yy==y){printf("%d",dis[xx+1][yy]); break;} 28 } 29 if(yy>-1000&&!bad[xx][yy-1]&&dis[xx][yy-1]==-1){ 30 q.push(make_pair(xx,yy-1)); dis[xx][yy-1]=dis[xx][yy]+1; 31 if(xx==x&&yy-1==y){printf("%d",dis[xx][yy-1]); break;} 32 } 33 if(yy<1000&&!bad[xx][yy+1]&&dis[xx][yy+1]==-1){ 34 q.push(make_pair(xx,yy+1)); dis[xx][yy+1]=dis[xx][yy]+1; 35 if(xx==x&&yy+1==y){printf("%d",dis[xx][yy+1]); break;} 36 } 37 } 38 return 0; 39 }
20160919