觉得浮夸了四年,漠然发现原来是浮躁了四年!

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         
复制代码

 

posted @   heat nan  阅读(236)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示