题意:从s到m的最短时间。(“o"不能走,‘#’走一个花两个单位时间,‘.'走一个花一个单位时间)
思路:广搜和优先队列。
1 #include <stdio.h> 2 #include <string.h> 3 #include <iostream> 4 #include <queue> 5 #define MAX 30 6 using namespace std; 7 8 struct pos 9 { 10 int x; 11 int y; 12 int step; 13 }; 14 15 bool operator<(const pos &a, const pos &b) 16 { 17 return a.step > b.step; 18 } 19 20 pos sp, ep; 21 char map[MAX][MAX]; 22 int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}, m, n, ti; 23 24 int bfs() 25 { 26 priority_queue<pos> q; 27 pos temp, t; 28 temp = sp; 29 temp.step = 0; 30 q.push(temp); 31 while(!q.empty()) 32 { 33 temp = q.top(); 34 q.pop(); 35 if(temp.step >= ti) 36 { 37 continue; 38 } 39 if(temp.x == ep.x && temp.y == ep.y && temp.step < ti) 40 { 41 return temp.step; 42 } 43 for(int i = 0; i < 4; i++) 44 { 45 t.x = temp.x + dir[i][0]; 46 t.y = temp.y + dir[i][1]; 47 if(t.x >= 0 && t.x < n && t.y >= 0 && t.y < m && map[t.x][t.y] != 'o') 48 { 49 if(map[t.x][t.y] == '.') 50 { 51 t.step = temp.step + 1; 52 map[t.x][t.y] = 'o'; 53 q.push(t); 54 } 55 else if(map[t.x][t.y] == '#') 56 { 57 t.step = temp.step + 2; 58 map[t.x][t.y] = 'o'; 59 q.push(t); 60 } 61 else if(map[t.x][t.y] == 'm') 62 { 63 t.step = temp.step + 1; 64 map[t.x][t.y] = 'o'; 65 q.push(t); 66 } 67 } 68 } 69 } 70 return -1; 71 } 72 73 int main() 74 { 75 scanf("%d%d%d", &ti, &m, &n); 76 int ans; 77 for(int i = 0; i < n; i++) 78 { 79 for(int j = 0; j < m; j++) 80 { 81 cin>>map[i][j]; 82 if(map[i][j] == 's') 83 { 84 sp.x = i; 85 sp.y = j; 86 } 87 if(map[i][j] == 'm') 88 { 89 ep.x = i; 90 ep.y = j; 91 } 92 } 93 } 94 ans = bfs(); 95 if(ans == -1) 96 { 97 printf("55555 "); 98 } 99 else 100 { 101 printf("%d ", ans); 102 } 103 return 0; 104 }