Problem link adress:http://acm.hdu.edu.cn/showproblem.php?pid=2645
//*****analysis*****//
The meaning of the problem is simple.
In the map consist of '0' and '1',find the nearest '1' for every '0'.
Clearly, we should use bfs work out every nearest station.Is it brute force?
1 #include<iostream> 2 #include<cstring> 3 #include<queue> 4 #include<string> 5 using namespace std; 6 char map[185][185]; 7 //int mark[185][185]; 8 int visit[185][185]; 9 int ans[185][185]; 10 struct node{ 11 int x,y,s; 12 }s[40000]; 13 int m,n; 14 int dir[4][2]={1,0,-1,0,0,1,0,-1}; 15 int bfs(int x1,int y1) 16 { 17 int x,y,i; 18 node cur,next; 19 queue<node>q; 20 memset(visit,0,sizeof(visit)); 21 cur.x=x1;cur.y=y1;cur.s=0; 22 q.push(cur); 23 visit[x1][y1]=1; 24 while(!q.empty()) 25 { 26 cur=q.front(); 27 q.pop(); 28 if(map[cur.x][cur.y]=='1') 29 return cur.s; 30 next.s=cur.s+1; 31 for(i=0;i<4;i++) 32 { 33 next.x=x=cur.x+dir[i][0]; 34 next.y=y=cur.y+dir[i][1]; 35 if(x>=0&&x<m&&y>=0&&y<n&&visit[x][y]==0) 36 { 37 q.push(next); 38 visit[x][y]=1; 39 } 40 } 41 } 42 return -1; 43 } 44 45 int main() 46 { 47 int i,j; 48 while(cin>>m>>n) 49 { 50 for(i=0;i<m;i++) 51 cin>>map[i]; 52 memset(mark,0,sizeof(mark)); 53 memset(ans,0,sizeof(ans)); 54 for(i=0;i<m;i++) 55 for(j=0;j<n;j++) 56 { 57 if(map[i][j]=='1') 58 { 59 ans[i][j]=0; 60 } 61 else 62 { 63 ans[i][j]=bfs(i,j); 64 } 65 } 66 67 for(i=0;i<m;i++) 68 { 69 for(j=0;j<n-1;j++) 70 { 71 cout<<ans[i][j]<<" "; 72 } 73 cout<<ans[i][j]<<endl; 74 } 75 } 76 return 0; 77 } 78 79