HDU2354 BFS+DFS
题意:找一条从第一行到最后一行的最短路
dfs用于重新建图。
bfs即可
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #include<queue> 3 #include<string.h> 4 #include<stdlib.h> 5 #include<map> 6 #include<algorithm> 7 using namespace std; 8 const int maxn = 22; 9 const int inf=9999999; 10 char mat[ maxn ][ maxn ]; 11 int my_time[ maxn ][ maxn ]; 12 int n,m; 13 const int dx[]={0,0,1,-1}; 14 const int dy[]={1,-1,0,0}; 15 int cnt,new_mat[ maxn ][ maxn ]; 16 17 int out( int x,int y ){ 18 if( x<0||x>=n||y<0||y>=m ) 19 return -1; 20 else 21 return 1; 22 } 23 void dfs( int x,int y,char now ){ 24 new_mat[ x ][ y ]=cnt; 25 for( int i=0;i<4;i++ ){ 26 int tx=x+dx[i]; 27 int ty=y+dy[i]; 28 if( out(tx,ty)==1&&new_mat[tx][ty]==-1&&mat[tx][ty]==now ){ 29 dfs( tx,ty,now ); 30 } 31 } 32 } 33 struct node{ 34 int x,y; 35 }; 36 void bfs( ){ 37 queue<node>q; 38 while(!q.empty()) 39 q.pop(); 40 for( int i=0;i<n;i++ ) 41 for( int j=0;j<m;j++ ) 42 my_time[ i ][ j ]=inf; 43 node now,next; 44 for( int i=0;i<m;i++ ){ 45 my_time[0][i]=0; 46 int x,y; 47 now.x=0,now.y=i; 48 q.push( now ); 49 } 50 51 while( !q.empty() ){ 52 now=q.front(),q.pop(); 53 for( int i=0;i<4;i++ ){ 54 next.x=now.x+dx[i]; 55 next.y=now.y+dy[i]; 56 if( out(next.x,next.y)==1&&my_time[next.x][next.y]>my_time[now.x][now.y]){ 57 if( new_mat[next.x][next.y]==new_mat[now.x][now.y] ){ 58 my_time[next.x][next.y]=my_time[now.x][now.y]; 59 q.push( next ); 60 } 61 else{ 62 my_time[next.x][next.y]=my_time[now.x][now.y]+1; 63 q.push( next ); 64 } 65 } 66 } 67 } 68 } 69 70 int main(){ 71 int ca; 72 scanf("%d",&ca); 73 while( ca-- ){ 74 scanf("%d%d",&n,&m); 75 for( int i=0;i<n;i++ ){ 76 scanf("%s",mat[i]); 77 } 78 cnt=1; 79 memset( new_mat,-1,sizeof( new_mat )); 80 for( int i=0;i<n;i++ ){ 81 for( int j=0;j<m;j++ ){ 82 if( new_mat[ i ][ j ]==-1 ){ 83 dfs( i,j,mat[i][j] ); 84 cnt++; 85 } 86 } 87 } 88 int ans=inf; 89 /* 90 for( int i=0;i<m;i++ ){ 91 if( i==0 ){ 92 bfs( 0,i ); 93 for( int j=0;j<m;j++ ) 94 ans=min(ans,my_time[n-1][j]); 95 } 96 else if( new_mat[0][i]!=new_mat[0][i-1] ){ 97 bfs( 0,i ); 98 for( int j=0;j<m;j++ ) 99 ans=min(ans,my_time[n-1][j]); 100 } 101 } 102 */ 103 bfs(); 104 for( int j=0;j<m;j++ ){ 105 ans=min(ans,my_time[n-1][j]); 106 } 107 printf("%d\n",ans+1); 108 } 109 return 0; 110 }
keep moving...