入门DFS
2016-01-31 23:44
381 查看
UVA_572: Oil Deposits
Time Limit: 3000 MS Memory Limit: 0 MB64bit IO Format: %lld
Description
The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes eachplot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous
pockets. Your job is to determine how many different oil deposits are contained in a grid.
Input
The input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwiseand
.
Following this are m lines of ncharacters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either `*', representing the absence of oil, or `@', representing an oil pocket.
Output
For each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.
Sample Input
1 1 * 3 5 *@*@* **@** *@*@* 1 8 @@****@* 5 5 ****@ *@@*@ *@**@ @@@*@ @@**@ 0 0
Sample Output
0 1 2 2
分析:先找到标记有@的位置,然后在以此为中心的距离为一的一个正方形里递归查找,并标记,再次查找时记得要以无标记为另一个条件。注意事项:
1.DFS函数里搜索时记得排除本身
2.注意输入时如何处理回车,否则会导致回车输入到矩阵中
代码:
#include<cstdio> #include<cstring> #include<cmath> int sig[110][110]; int n, m; char mat[110][110]; void dfs(int x, int y,int id) { if (x<0 || x>n || y<0 || y>m||sig[x][y] > 0||mat[x][y]!='@') return; sig[x][y] = id; int dx, dy; for (dx = -1; dx <= 1; dx++) for (dy = -1; dy <= 1; dy++) if(dx!=0||dy!=0) dfs(x + dx, y + dy, id); } int main() { int i, j,id; while (scanf("%d%d", &n, &m) != EOF&&n) { getchar(); memset(sig, 0, sizeof sig); for (i = 0; i < n; i++) scanf("%s", &mat[i]); for (i = 0, id = 0; i < n; i++) for (j = 0; j < m; j++) if (sig[i][j] == 0 && mat[i][j] == '@') dfs(i, j, ++id); printf("%d\n", id); } return 0; }
相关文章推荐
- Android第一行代码小结
- 火车头采集器破解版
- 学习路线
- day3Scala函数式编程
- 医院业务系统设计(三) --- 患者管理之预约系统
- object-oriented第二次作业(1)
- 声音设备接口
- 开通博客,好好加油
- Android笔记-canvas与自定义view相关内容
- 并查集-HDU-1213-How Many Tables
- STM32F10X PWM配置例程详解,测试无误
- 世间本无传奇
- 函数式编程
- 关于1.11 题后问题的分析
- js 封装ajax
- mycat读写分离与主从切换
- 阿里云 Centos 7 PHP7环境配置 LNMP
- java项目——大数据量的处理
- 从零快速搭建Android项目
- 《VR入门系列教程》之12---转换矩阵