题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=1100
BFS + 优先队列! 自定义优先级!!!!!
代码:
#include <cstdio> #include <queue> #include <cstring> using namespace std; typedef struct Node { int x,y; char c; int cost; } Node; struct cmp { bool operator()(Node a,Node b) { return a.cost > b.cost; } }; int dx[] = {-1,0,1,0}; int dy[] = {0,1,0,-1}; char s[105][105]; bool v[105][105]; int stx,sty,enx,eny; int flag; int n,m; priority_queue<Node,vector<Node>,cmp> pq; int bfs(int x,int y) { Node first; first.x = x; first.y = y; first.c = 's'; first.cost = 0; pq.push(first); while(!pq.empty()) { Node head = pq.top(); //printf("%d %d\n",head.x,head.y); pq.pop(); for(int i = 0; i < 4; ++i) { Node t; t.x = head.x + dx[i]; t.y = head.y + dy[i]; t.c = s[t.x][t.y]; if(t.x == enx && t.y == eny) { flag = 1; return head.cost; break; } if(t.x>=0&&t.x<n&&t.y>=0&&t.y<m&&t.c!='#' && !v[t.x][t.y]) { v[t.x][t.y] = true; t.cost = head.cost + (t.c - 'A' + 1); pq.push(t); } } if(flag) break; } return -1; } void clear() { while(!pq.empty()) pq.pop(); } int main() { int _; scanf("%d",&_); while(_--) { memset(v,false,sizeof v); scanf("%d%d",&n,&m); for(int i = 0; i < n; ++i) scanf("%s",s[i]); for(int i = 0; i < n; ++i) for(int j = 0; j < m; ++j) if(s[i][j] == 's') { stx = i; sty = j; } else if(s[i][j] == 'l') { enx = i; eny = j; } flag = 0; v[stx][sty] = true; int ans = bfs(stx,sty); printf("%d\n",ans); clear(); } return 0; }