ECNU1104-BFS

简单的BFS
题意:多起点多终点

 1 /*
 2 简单的BFS
 3 题意:多起点多终点
 4 */
 5 #include<stdio.h>
 6 #include<string.h>
 7 #include<stdlib.h>
 8 #include<queue>
 9 #include<algorithm>
10 using namespace std;
11  
12 const int maxn = 184;
13 const int inf = 0x3f3f3f3f;
14  
15 int dis[ maxn ][ maxn ];
16 char mat[ maxn ][ maxn ];
17 const int dx[]={0,0,1,-1};
18 const int dy[]={1,-1,0,0};
19  
20 queue<int>q;
21  
22 void init(){
23     memset( dis,0x3f,sizeof( dis ) );
24     while( !q.empty() )
25         q.pop();
26 } 
27  
28 bool in( int x,int y,int n,int m ){
29     if( x>=0&&x<n && y>=0&&y<m ) return true;
30     else return false;
31 }
32  
33 void bfs( /*int x,int y,*/int n,int m ){
34     /*int curx = x;
35     int cury = y;
36     int curt = 0;
37     q.push( curx );
38     q.push( cury );
39     q.push( curt );*/
40     while( !q.empty() ){
41         int curx = q.front();q.pop();
42         int cury = q.front();q.pop();
43         int curt = q.front();q.pop();
44         for( int i=0;i<4;i++ ){
45             int nx = curx+dx[i];
46             int ny = cury+dy[i];
47             int nt = curt + 1;
48             if( in( nx,ny,n,m ) && dis[ nx ][ ny ]>nt ){
49                 dis[ nx ][ ny ] = nt;
50                 q.push( nx );
51                 q.push( ny );
52                 q.push( nt );
53             }
54         }
55     }
56     return ;
57 }
58  
59 int main(){
60     int n,m;
61     //freopen( "in.txt","r",stdin );
62     while( scanf("%d%d",&n,&m)==2 ){
63         init();
64         for( int i=0;i<n;i++ ){
65             scanf("%s",mat[i]);
66             for( int j=0;j<m;j++ ){
67                 if( mat[ i ][ j ]=='1' ){
68                     dis[ i ][ j ] = 0;
69                     q.push( i );
70                     q.push( j );
71                     q.push( 0 );
72                 }
73             }
74         }
75         bfs( n,m );
76         for( int i=0;i<n;i++ ){
77             for( int j=0;j<m;j++ ){
78                 if( j==0 ) printf("%d",dis[ i ][ j ]);
79                 else printf(" %d",dis[ i ][ j ]);
80             }
81             printf("\n");
82         }
83     }
84     return 0;
85 }
View Code

posted @ 2013-10-20 17:25  xxx0624  阅读(302)  评论(0编辑  收藏  举报