Oil Deposits

来源:互联网 发布:罗技逆战宏编程 编辑:程序博客网 时间:2024/05/29 19:47

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 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
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

这个题目最坑的地方就是在样例中,5 5的后面有一个额外的空格,恰好我跟一个朋友说起这件事,他告诉我一个非常神奇的写法

scanf(" %c",&map[i][j]);
就是在%c之前加一个空格,这样可以清除掉不必要的输入

#include<stdio.h>#include<string.h>#include<iostream>void dfs(int x,int y);bool check(int x,int y);bool book[105][105];char map[105][105];int n,m;int main(){while(scanf("%d%d",&m,&n),m){int i,j,cnt;memset(map,0,sizeof(map));memset(book,false,sizeof(book));cnt=0;for(i=0;i<m;i++){for(j=0;j<n;j++){scanf(" %c",&map[i][j]);}}for(i=0;i<m;i++){for(j=0;j<n;j++){if(map[i][j]=='@'&&book[i][j]==false){dfs(i,j);cnt++;}}}printf("%d\n",cnt); }return 0;}void dfs(int x,int y){int i,j;if(!check(x,y))return;for(i=-1;i<=1;i++){for(j=-1;j<=1;j++){if(i!=0||j!=0){book[x][y]=true;if(check(x+i,y+j))dfs(x+i,y+j);}}}} bool check(int x,int y){if(x>=0&&x<m&&y>=0&&y<n&&book[x][y]==false&&map[x][y]=='@'){return true;}return false;}



原创粉丝点击