poj2312Battle City BFS

题意: M行N列矩阵, 'Y'表示开始位置, 'T'表示目标位置, 从开始位置到目标位置至少需要走多少步,其中, 'S', 'R'表示不能走, 'B' 花费为2, 'E'花费为1.

思路:纯 BFS.

很久没写BFS, 刚写居然不知道从何下手...

 1 #include <iostream>

 2 #include <queue>

 3 using namespace std;

 4 

 5 struct postion

 6 {

 7     int i, j;

 8     postion operator+(postion p)

 9     {

10         postion t;

11         t.i = this->i+ p.i;

12         t.j = this->j+ p.j;

13         return t;

14     }

15 };

16 

17 postion dir[] = {1,0, -1,0, 0,1, 0,-1};

18 

19 int step[305][305];

20 //bool used[305][305];

21 queue<postion>que;

22 char map[305][305];

23 postion start, target;

24 int M, N;

25 

26 int main()

27 {

28     int  i, j;

29     while (cin>>M>>N && M+N)

30     {

31         for (i=0; i<M; i++)

32             for (j=0; j<N; j++)

33             {

34                 cin>>map[i][j];

35                 step[i][j] = INT_MAX;

36                 if (map[i][j] == 'Y')

37                     start.i = i, start.j = j;

38                 else if (map[i][j] == 'T')

39                     target.i = i, target.j = j;

40             }

41             //memset(used, false, sizeof(used));

42             //memset(step, 0, sizeof(step));

43             //used[start.i][start.j] = true;

44             step[start.i][start.j] = 0;

45             while (!que.empty())que.pop();

46             que.push(start);

47             postion tmp, t;

48             int sp;

49             while (!que.empty())

50             {

51                 tmp = que.front();

52                 que.pop();

53                 for (i=0; i<4; i++)

54                 {

55                     t = tmp + dir[i];

56                     if (t.i<0 || t.i>=M || t.j<0 || t.j>=N || map[t.i][t.j] == 'R' || map[t.i][t.j] == 'S')

57                         continue;

58                     if (map[t.i][t.j] == 'E')

59                         sp = 1;

60                     if (map[t.i][t.j] == 'B')

61                         sp = 2;

62                     if (step[t.i][t.j] > step[tmp.i][tmp.j] + sp)

63                     {

64                         step[t.i][t.j] = step[tmp.i][tmp.j] + sp;

65                         que.push(t);

66                     }

67                 }

68             }

69             if (step[target.i][target.j] == INT_MAX)

70                 step[target.i][target.j] = -1;

71             cout<<step[target.i][target.j]<<endl;

72     }

73     return 0;

74 }
View Code

 

你可能感兴趣的:(poj)