POJ2225+BFS

简单的BFS   1a

 1 /*

 2 从起点到终点

 3 */

 4 #include<stdio.h>

 5 #include<string.h>

 6 #include<stdlib.h>

 7 #include<algorithm>

 8 #include<queue>

 9 #include<iostream>

10 using namespace std;

11 

12 const int maxn = 12;

13 const int Max = 99999999;

14 char mat[ maxn ][ maxn ][ maxn ];

15 int vis[ maxn ][ maxn ][ maxn ];

16 const int dx[]={0,0,1,-1,0,0};

17 const int dy[]={1,-1,0,0,0,0};

18 const int dz[]={0,0,0,0,1,-1};

19 struct node{

20     int x,y,z,ti;

21 }my_start,my_end;

22 

23 bool ok( node cur ){

24     if( mat[ cur.z ][ cur.x ][ cur.y ]=='X'||vis[ cur.z ][ cur.x ][ cur.y ]==1 )

25         return false;

26     else 

27         return true;

28 }

29 

30 bool inside( node cur,int n ){

31     if( cur.x>=0&&cur.x<n&&cur.y>=0&&cur.y<n&&cur.z>=0&&cur.z<n )

32         return true;

33     else

34         return false;

35 }

36 

37 int bfs( int n ){

38     if( my_start.x==my_end.x&&my_start.y==my_end.y&&my_start.z==my_end.z )

39         return 0;

40     queue<node>q;

41     node cur,nxt;

42     int ans = Max;

43     cur.x = my_start.x;

44     cur.y = my_start.y;

45     cur.z = my_start.z;

46     cur.ti = 0;

47     vis[ cur.z ][ cur.x ][ cur.y ] = 1;

48     q.push( cur );

49     while( !q.empty() ){

50         cur = q.front();

51         q.pop();

52         if( cur.x==my_end.x&&cur.y==my_end.y&&cur.z==my_end.z ){

53             ans = min( ans,cur.ti );

54         }

55         for( int i=0;i<6;i++ ){

56             nxt = cur;

57             nxt.ti ++;

58             nxt.x += dx[i];

59             nxt.y += dy[i];

60             nxt.z += dz[i];

61             if( inside( nxt,n )==false||ok( nxt )==false ) continue;

62             vis[ nxt.z ][ nxt.x ][ nxt.y ] = 1;

63             q.push( nxt );

64         }

65     }

66 

67     if( ans>=Max ) return -1;

68     else return ans;

69 }

70 

71 int main(){

72     int N;

73     char str[ maxn ];

74     while( scanf("%s%d",str,&N)!=EOF ){

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

76         for( int i=0;i<N;i++ ){

77             for( int j=0;j<N;j++ ){

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

79             }

80         }

81         //mat[i][j][k] 层 行 列

82         scanf("%d%d%d",&my_start.y,&my_start.x,&my_start.z);

83         scanf("%d%d%d",&my_end.y,&my_end.x,&my_end.z);

84         //列 行 层

85         scanf("%s",str);

86         int ans = bfs( N );

87         if( ans==-1 ) printf("NO ROUTE\n");

88         else printf("%d %d\n",N,ans);

89     }

90     return 0;

91 }
View Code

 

你可能感兴趣的:(poj)