先来普及一发优先队列,
是常用到BFS里面的;
写法大概是:
struct node
{
int x,y;
int step;
friend bool operator<(node a,node b){
return a.step>b.step;
}
};
其目的是先到的进行先调用的思想;
在queue的用法稍微加了新的东西,
priority_queue<node>XXX;'
其余的还是老套路;这个题为了比较大小,先把所有初始值变味了1,然后搜索到后才置为0方便和step比较,存储;
AC代码:
#include <iostream> #include <queue> #include <string.h> #include <stdio.h> using namespace std; int n , m , step; int x1,x2,y1,y2; int vis[205][205]; char map[200][200]; int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}}; struct node{ int x; int y; int step; friend bool operator<(node n1,node n2) { return n2.step<n1.step; } }; bool check (int x , int y ) { if(x<0||x>=n||y<0||y>=m||map[x][y]=='#') return true; return false; } int bfs() { int i ; priority_queue<node>Q; node a, b ; a.x=x1; a.y=y1; a.step=0; Q.push(a); vis[x1][y1]=0; while(!Q.empty()) { a=Q.top(); Q.pop(); if(a.x==x2&&a.y==y2) return a.step; for(i=0;i<4;i++) { b=a; b.x+=dir[i][0]; b.y+=dir[i][1]; if(check(b.x,b.y)) continue; b.step++; if(map[b.x][b.y]=='x') b.step++; if(vis[b.x][b.y]>=b.step) { vis[b.x][b.y]=b.step; Q.push(b); } } } return 0 ; } int main() { int i , j ; while(cin>>n>>m) { for(i=0;i<n;i++) { for(j=0;j<m;j++) { cin>>map[i][j]; } } for(i=0;i<n;i++) { for(j=0;j<m;j++) { if(map[i][j]=='r') { x1=i;y1=j; } else if(map[i][j]=='a') { x2=i;y2=j; } } } memset(vis,1,sizeof(vis)); int ans = 0 ; ans = bfs(); if(ans) { cout<<ans<<endl; } else printf("Poor ANGEL has to stay in the prison all his life.\n"); } return 0 ; }
PS:这个题是最短路,优先队列复杂度小,但是实际不一定跑的快;
优先队列插入是log的,裸队列是O1的;