入门DFS

来源:互联网 发布:国产数据集成工具 编辑:程序博客网 时间:2024/06/15 22:58

UVA_572: Oil Deposits

Time Limit: 3000 MS  Memory Limit: 0 MB  64bit 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 each plot 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; otherwise $1 \le m \le 100$ and $1 \le n \le 100$. 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

0122

分析:先找到标记有@的位置,然后在以此为中心的距离为一的一个正方形里递归查找,并标记,再次查找时记得要以无标记为另一个条件。注意事项:
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;}

0 0