HDU 1026 Ignatius and the Princess I (BFS)

题目链接

题意 : 从(0,0)点走到(N-1,M-1)点,问最少时间。

思路 : BFS、、、、、

 1 #include <stdio.h>

 2 #include <string.h>

 3 #include <queue>

 4 #include <iostream>

 5 

 6 using namespace std ;

 7 

 8 struct node

 9 {

10     int x,y ;

11     int tim ;

12     friend bool operator < (node a,node b)

13     {

14         return a.tim > b.tim ;

15     }

16 } temp,temp1;

17 int N,M ,t;

18 char mapp[110][110] ;

19 int vis[110][110] ;

20 int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}} ;

21 

22 int BFS()

23 {

24     temp.x = 0 ;

25     temp.y = 0 ;

26     temp.tim = 0 ;

27     priority_queue<node>Q ;

28     Q.push(temp) ;

29    // vis[0][0] = true ;

30     while(Q.size())

31     {

32         temp = Q.top() ;

33         Q.pop() ;

34         if(temp.x == N-1 && temp.y == M-1) return temp.tim ;

35         for(int i = 0 ; i < 4 ; i++)

36         {

37             temp1.x = temp.x+dir[i][0] ;

38             temp1.y = temp.y+dir[i][1] ;

39             if(temp1.x >= 0 && temp1.y >= 0 && temp1.x <= N-1 && temp1.y <= M-1 && vis[temp1.x][temp1.y] == -1 && mapp[temp1.x][temp1.y] != 'X')

40             {

41                 vis[temp1.x][temp1.y] = temp.x*M+temp.y ;

42                 if(mapp[temp1.x][temp1.y] == '.')

43                     temp1.tim = temp.tim+1 ;

44                 else

45                     temp1.tim = temp.tim + mapp[temp1.x][temp1.y]-'0'+1 ;

46                 Q.push(temp1) ;

47             }

48         }

49     }

50     return -1 ;

51 }

52 void print(int x,int y)

53 {

54     if(x == 0 && y == 0)

55         return ;

56     int xx = vis[x][y]/M ;

57     int yy = vis[x][y]%M ;

58     print(xx,yy) ;

59     printf("%ds:(%d,%d)->(%d,%d)\n",t++,xx,yy,x,y) ;

60     if(mapp[x][y] >= '0' && mapp[x][y] <= '9')

61     {

62         while(mapp[x][y] -'0' > 0)

63         {

64             printf("%ds:FIGHT AT (%d,%d)\n",t++,x,y) ;

65             mapp[x][y] -- ;

66         }

67     }

68 }

69 int main()

70 {

71     while(~scanf("%d %d",&N,&M))

72     {

73         for(int i = 0 ; i < N ; i++ )

74             scanf("%s",mapp[i]) ;

75         memset(vis,-1,sizeof(vis)) ;

76         int timee = BFS() ;

77         if(timee == -1)

78         {

79             printf("God please help our poor hero.\nFINISH\n") ;

80         }

81         else

82         {

83             t = 1 ;

84             printf("It takes %d seconds to reach the target position, let me show you the way.\n",timee) ;

85             print(N-1,M-1) ;

86             printf("FINISH\n") ;

87         }

88     }

89     return 0 ;

90 }
View Code

 

你可能感兴趣的:(HDU)