AOJ 0118: Property Disribution(dfs)
来源:互联网 发布:oss 阿里云 编辑:程序博客网 时间:2024/05/16 19:41
原题地址:点击打开链接
在H * W的矩形果园里有苹果、梨、蜜柑三种果树, 相邻(上下左右)的同种果树属于同一个区域,给出果园的果树分布,求总共有多少个区域。 (原题的样图中苹果为リ,梨为カ,蜜柑为ミ, 图中共10个区域)
输入:
多组数据,每组数据第一行为两个整数H,W(H <= 100, W <= 100),H =0 且W = 0代表输入结束。以下H行W列表示果园的果树分布, 苹果是@,梨是#, 蜜柑是*。
输出:
对于每组数据,输出其区域的个数。
分析:迷宫问题。对于每一个格子,可以用深度优先搜索把相同果树的格子遍历并标记。也就是说,每做一次DFS,消灭掉一个区域。只需要遍历果园,对每一个未被标记的格子做DFS,做DFS的次数就是果园的区域数。这里不需要另外用其他数组标记格子已访问,只需要将格子的元素改为一个不会出现的元素如1即可。
#include <stdio.h>#define MAX_W 100#define MAX_H 100int w, h;int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};char m[MAX_H][MAX_W + 1];void dfs(int x, int y, int t){m[x][y] = 0;for(int i = 0; i < 4; i ++){int nx = x + dx[i], ny = y + dy[i];if(nx >= 0 && nx < h && ny >= 0 && ny < w && t == m[nx][ny])dfs(nx, ny, t);}}void solve(){int flag = 0, ans = 0;for(int i = 0; i < h; i ++){for(int j = 0; j < w; j ++)if(0 != m[i][j]){dfs(i, j, m[i][j]);ans ++;}}printf("%d\n", ans);}int main(){scanf("%d%d", &w, &h);for(int i = 0; i < h; i ++)scanf("%s", m[i]);if(w || h)solve();return 0;}
思路:
对于每一个果树用dfs搜索附近相同的果树,并做上标记,则dfs的次数即是答案了
1 0
- AOJ 0118: Property Disribution(dfs)
- AOJ 0118 Property Distribution (dfs)
- AOJ 0118: Property Distribution (简单DFS)
- AOJ 0118 Property Distribution (DFS)
- [DFS] AOJ 0118 Property Distribution
- Aoj 0118 Property Distribution【dfs】
- AOJ 0118 Property Distribution 【DFS】
- AOJ 0118 Property Distribution(dfs 求连通块)
- AOJ 0033 ball+AOH 0118Property Distribution (DFS)
- AOJ 0118 Property Distribution (果园分类)
- AOJ--0118 Property Distribution
- AOJ 0118 Property Distribution (BFS)
- AOJ 0118 Property Distribution 题解
- aizu/aoj-0118-Property Distribution
- AOJ 0033 Ball (dfs)
- AOJ 0525 Osenbei (dfs)
- AOJ 0033: Ball(dfs )
- 【AOJ 869】迷宫(DFS)
- DS-5 Development Studio
- 工欲善其事必先利其器
- 飛飛(三十三)深复制体验
- 百度地图API之JavaScript 开源库1
- 学好C语言的推荐途径
- AOJ 0118: Property Disribution(dfs)
- JavaScript字符串操作
- iOS多线程
- 迁移discuz
- Android Service 远程服务
- View的事件分发和工作机制
- enum 在c++中的使用
- 用html5新增的js媒体 API手写的一个视频播放器
- 完美解决myBase Desktop 破解