题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2822
#include<iostream> #include<queue> #include<cstring> using namespace std; int len,wid; char map[1010][1010]; const int dir[4][2]={{1,0},{0,1},{0,-1},{-1,0}}; bool vis[1010][1010]; struct node{ int x,y,step; friend bool operator < (const node& a,const node& b){ return a.step>b.step; } }s,e; int bfs(){ priority_queue<node> q; node u,tmp; memset(vis,0,sizeof(vis));//判重 int nx,ny; q.push(s); while(!q.empty()) { u=q.top(); q.pop(); if(u.x==e.x&&u.y==e.y) return u.step; for(int i=0;i<4;i++) { nx=u.x+dir[i][0]; ny=u.y+dir[i][1]; if(nx<0 || nx>=len || ny<0 || ny>=wid || vis[nx][ny]) continue; tmp.x=nx; tmp.y=ny; tmp.step=u.step; if(map[nx][ny]!='X') tmp.step++; vis[nx][ny]=1; q.push(tmp); } } return -1;//如果无法到达(肯定没这种情况) } int main(){ while(cin>>len>>wid){ if(!(len|wid)) break; for(int i=0;i<len;i++){ cin>>map[i]; getchar(); } cin>>s.x>>s.y; cin>>e.x>>e.y; s.x--;s.y--;e.x--;e.y--;//注意!!!! s.step=e.step=0; cout<<bfs()<<endl; } return 0; } /* 6 6 ..X... XXX.X. ....X. X..... X..... X.X... 3 5 6 3 0 0 */