nyoj 坦克大战 (优先队列)

BFS题目。输入完图之后可以先预处理一下,然后用优先队列解决。

 1 #include<iostream>

 2 #include<cstdio>

 3 #include<cstdlib>

 4 #include<cstring>

 5 #include<string>

 6 #include<queue>

 7 #include<algorithm>

 8 #include<map>

 9 #include<iomanip>

10 #include<climits>

11 #include<string.h>

12 #include<cmath>

13 #include<stdlib.h>

14 #include<vector>

15 #include<set>

16 #define INF 1e7

17 #define MAXN 100010

18 #define maxn 111

19 #define maxm 1000

20 #define Mod 1000007

21 #define MIN(a,b) (a < b ? a : b)

22 #define MAX(a,b) (a > b ? a : b)

23 #define mem(a) memset(a,0,sizeof(a))

24 using namespace std;

25 typedef long long LL;

26 int n, m;

27 int sx, sy, fx, fy;

28 char G[333][333];

29 int mp[333][333]; 

30 int vis[333][333];

31 int dx[] = { 1, -1, 0, 0 }, dy[] = { 0, 0, 1, -1 };

32 

33 struct node {

34     int x, y, step;

35     bool operator <(const node a) const {

36         return step > a.step;

37     }

38 };

39 

40 bool check(int x, int y)

41 {

42     if (vis[x][y] || x < 0 || y < 0 || x >= n || y >= m)

43         return true;

44     return false;

45 }

46 

47 int bfs()

48 {

49     priority_queue<node> q;

50     q.push({ sx, sy, 0 });

51     vis[sx][sy] = 1;

52     while (!q.empty()) {

53         node now = q.top();

54         q.pop();

55         if (now.x == fx && now.y == fy)

56             return now.step;

57         node next;

58         for (int i = 0; i < 4; ++i) {

59             next.x = now.x + dx[i];

60             next.y = now.y + dy[i];

61             next.step = now.step;

62             if (check(next.x, next.y)) continue;

63             if (mp[next.x][next.y] != -1) {

64                 q.push({ next.x, next.y, next.step + mp[next.x][next.y] });

65                 vis[next.x][next.y] = 1;

66             }

67         }

68     }

69     return -1;

70 }

71 

72 int main()

73 {

74     while (~scanf("%d%d",&n,&m), n + m) {

75         memset(vis,0,sizeof(vis));

76         memset(mp,0,sizeof(mp));

77         for (int i = 0; i < n; ++i) {

78             scanf("%s", G[i]);

79             for (int j = 0; j < m; ++j) {

80                 if (G[i][j] == 'Y')

81                     sx = i, sy = j;

82                 else if (G[i][j] == 'T')

83                     fx = i, fy = j;

84             }

85         }

86         for (int i = 0; i < n; ++i)

87             for (int j = 0; j < m; ++j) {

88                 if (G[i][j] == 'S' || G[i][j] == 'R') mp[i][j] = -1;

89                 else if (G[i][j] == 'B') mp[i][j] = 2;

90                 else if (G[i][j] == 'E' || G[i][j] == 'T') mp[i][j] = 1;

91             }

92         cout << bfs() << endl;

93     }

94     return 0;

95 }

 

你可能感兴趣的:(优先队列)