UVA

来源:互联网 发布:debian 没有yum 编辑:程序博客网 时间:2024/06/08 00:43

题目:
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 ≤ m ≤ 100 and 1 ≤ n ≤ 100. Following this are m lines of n characters 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 Input1 1*3 5*@*@***@***@*@*1 8@@****@*5 5****@*@@*@*@**@@@@*@@@**@0 0Sample Output0122

题目大意:求@联通块的个数,8个方向都算联通。
具体思路: 遍历n*m 找到一个@块,就将它附近能走到的位置标记一波。 这个题我第一次看的时候完全没有思路,无法动手,现在写紫书,感觉真的不难。

代码:

#include <cstdio>#include <iostream>#include <cstring>#include <algorithm>#include <queue>#include <set>#include <map>using namespace std;#define Pair pair<int,int>int ans = 0;int oil[105][105];int way[8][2] = {0,1,0,-1,1,0,-1,0,-1,1,-1,-1,1,-1,1,1};int m,n;int bfs(int i,int j){    queue<Pair> Q;    Q.push(Pair(i,j));    oil[i][j] = 0;    while(!Q.empty())    {        Pair temp = Q.front();        Q.pop();        oil[temp.first][temp.second] = 0;        for(int i = 0; i < 8;i++)        {            Pair change = Pair(temp.first+way[i][0],temp.second+way[i][1]);            if(change.first >= 0 && change.first < m               && change.second < n && change.second >= 0 &&              oil[change.first][change.second] == 1)                    Q.push(change);        }    }}int main(){    while(~scanf("%d%d",&m,&n) && m)    {        ans = 0;        memset(oil,0,sizeof(oil));        for(int i = 0; i < m ; i++)        {            char s[105];            scanf("%s",s);            for(int j = 0; j < n; j++)                if(s[j] == '@')                    oil[i][j] = 1;        }        for(int i = 0; i < m; i++)        for(int j = 0; j < n ; j++)        {            if(oil[i][j] == 1)            {                bfs(i,j);                ans++;            }        }        printf("%d\n",ans);    }    return 0;}
0 0
原创粉丝点击