题目链接:hdu4198
题目大意:求起点S到出口的最短花费,其中#为障碍物,无法通过,‘.’的花费为1 ,@的花费为d+1。
需注意起点S可能就是出口,因为没考虑到这个,导致WA很多次.......
#include<stdio.h> #include<string.h> #include<algorithm> #include<queue> using namespace std; char map[505][505]; int d[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; int n,m,t; int begin_x,begin_y,end_x,end_y; struct node { int x,y,time; friend bool operator < (node a,node b) { return a.time > b.time; } }; void bfs() { priority_queue <node> q; node s,temp; s.x = begin_x; s.y = begin_y; s.time = 0; map[begin_x][begin_y] = '#'; q.push(s); while(!q.empty()) { temp = q.top(); q.pop(); if(temp.x == end_x && temp.y == end_y) { printf("%d ",temp.time + 1); return; } for(int i = 0 ; i < 4 ; i ++) { s.x = temp.x + d[i][0]; s.y = temp.y + d[i][1]; if(s.x < 0 || s.x >= n || s.y < 0 || s.y >= m || map[s.x][s.y] == '#') continue; if(map[s.x][s.y] == '.') s.time = temp.time + 1; else s.time = temp.time + t + 1; map[s.x][s.y] = '#'; q.push(s); } } } int main() { int T,i,j; scanf("%d",&T); while(T--) { scanf("%d%d%d",&n,&m,&t); for(i = 0 ; i < n ; i ++) { scanf("%s",map[i]); for(j = 0 ; j < m ; j ++) { if(map[i][j] == 'S') { begin_x = i; begin_y = j; } if( (i == 0 || i == n - 1 || j == 0 || j == m - 1) && map[i][j] != '#')//刚开始用的else if,没有考虑起点也是终点的情况,WA了很多次 { end_x = i; end_y = j; } } } bfs(); } return 0; }