hdu 2645(find the nearest station) bfs+brute force

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?

 

 

 

 

View Code
 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         

 

转载于:https://www.cnblogs.com/heat-man/archive/2013/03/02/2941098.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值