博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
UVa 572 - Oil Deposits
阅读量:7099 次
发布时间:2019-06-28

本文共 3217 字,大约阅读时间需要 10 分钟。

  给一个m*n的矩阵,数字是0或是1,统计其中八连块的个数,和《算法竞赛入门经典》6.4.1黑白图像一样,应该是那个的原型吧。

  代码如下:

View Code
1 #include 
2 #include
3 4 const int maxn = 105; 5 int mat[maxn][maxn], vis[maxn][maxn]; 6 7 void dfs(int x, int y) 8 { 9 if(vis[x][y] || !mat[x][y]) return;10 vis[x][y] = 1;11 dfs(x-1, y-1); dfs(x-1, y); dfs(x-1, y+1);12 dfs(x, y-1); dfs(x, y+1);13 dfs(x+1, y-1); dfs(x+1, y); dfs(x+1, y+1);14 }15 16 int main()17 {18 #ifdef LOCAL19 freopen("in", "r", stdin);20 #endif21 int m, n;22 while(scanf("%d%d", &m , &n) != EOF && m)23 {24 char s[maxn];25 memset(mat, 0, sizeof(mat));26 memset(vis, 0, sizeof(vis));27 for(int i = 0; i < m; i++)28 {29 scanf("%s", s);30 for(int j = 0; j < n; j++)31 {32 if(s[j] == '*') mat[i+1][j+1] = 0;33 else if(s[j] == '@') mat[i+1][j+1] = 1;34 }35 }36 int cnt = 0;37 for(int i = 1; i <= m; i++)38 for(int j = 1; j <= n; j++)39 if(!vis[i][j] && mat[i][j])40 {41 cnt++;42 dfs(i, j);43 }44 printf("%d\n", cnt);45 }46 return 0;47 }

   上面是用递归的方式实现的,也可用显式栈来代替递归,代码如下:

View Code
1 #include 
2 #include
3 #include
4 using namespace std; 5 6 const int maxn = 105; 7 int mat[maxn][maxn], vis[maxn][maxn]; 8 int m, n; 9 10 const int dir[][2] = { {
1, 1}, {
1, 0}, {
1, -1}, {
0, 1}, {
0, -1}, {-1, 1}, {-1, 0}, {-1,-1} };11 12 struct Pos13 {14 int x, y;15 };16 17 void dfs(int x, int y)18 {19 stack
s;20 Pos t;21 t.x = x;22 t.y = y;23 s.push(t);24 while(!s.empty())25 {26 t = s.top();27 s.pop();28 int x = t.x, y = t.y;29 for(int i = 0; i < 8; i++)30 {31 int nx, ny;32 nx = x + dir[i][0];33 ny = y + dir[i][1];34 if(nx >= 0 && nx < m && ny >= 0 && ny < n)35 if(mat[nx][ny] && !vis[nx][ny])36 {37 t.x = nx;38 t.y = ny;39 s.push(t);40 vis[nx][ny] = 1;41 }42 }43 }44 }45 46 47 int main()48 {49 #ifdef LOCAL50 freopen("in", "r", stdin);51 #endif52 while(scanf("%d%d", &m, &n) != EOF && m)53 {54 char s[maxn];55 memset(mat, 0, sizeof(mat));56 memset(vis, 0, sizeof(vis));57 for(int i = 0; i < m; i++)58 {59 scanf("%s", s);60 for(int j = 0; j < n; j++)61 if(s[j] == '@') mat[i][j] = 1;62 }63 int cnt = 0;64 for(int i = 0; i < m; i++)65 for(int j = 0; j < n; j++)66 if(!vis[i][j] && mat[i][j])67 {68 cnt++;69 dfs(i, j);70 }71 printf("%d\n", cnt);72 }73 return 0;74 }

 

转载于:https://www.cnblogs.com/xiaobaibuhei/archive/2013/04/25/3042676.html

你可能感兴趣的文章
Unix下启动停止Oracle服务命令
查看>>
软银将推出虚拟现实观赛服务
查看>>
explain mysql性能优化
查看>>
你真的会写Hello World吗
查看>>
深入Spring Boot: 怎样排查 java.lang.ArrayStoreException
查看>>
React 列表、键值与表单
查看>>
阿里出新零售“王炸”:手淘和钉钉打通,7万导购已受益
查看>>
Hibernate小解惑
查看>>
Javascript 开启浏览器全屏模式
查看>>
Java代码规范
查看>>
你不知道的JavaScript·第一部分
查看>>
松下CEO发话,期盼与特斯拉进一步合作自动驾驶
查看>>
Spring集成Jedis(不依赖spring-data-redis)(单机/集群模式)(待实践)
查看>>
张高兴的 Xamarin.Forms 开发笔记:Android 快捷方式 Shortcut 应用
查看>>
“百万年薪一将难求”,新零售人才争夺战怎么打?
查看>>
Firefox 66 发布,阻止网站自动播放声音
查看>>
介绍两个好玩的和Github相关的Chrome扩展
查看>>
他们经营天猫一半的店铺,或迎来史上最大机遇
查看>>
GMGC昆山数娱峰会:VR爆发,差的不只是一层窗户纸
查看>>
8Manage 助力平阳县交通运输局实现招标流程电子化管理
查看>>