DFS+BFS練習 C題
C - Oil Deposits
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 Input
1 1 * 3 5 *@*@* **@** *@*@* 1 8 @@****@* 5 5 ****@ *@@*@ *@**@ @@@*@ @@**@ 0 0
Sample Output
0
1
2
2
(複製貼上的)題意:
和迷宮的輸入差不多,‘*’是牆,‘@’是油田,以一個油田為中心,如果它的東南西北一個各個角落,一共八個方向也有油田的話,這些油田就算作一個油田。
(複製貼上的)分析:
查詢到‘@’的位置,找到一個,油田加1,對找到的‘@’的四周進行DFS查詢,剛開始我以為和迷宮的做法差不多,我把查詢過的地方用一個數組標記一下,後來測試結果不對,
才發現在某一次存在題意中的相鄰油田時,在主函式中會加1,而實際上這塊油田我已經計算進去了,這樣就重複了。正確的做法應該是把計算進去的那塊油田變為‘*’,這樣就不存在重複計算了!!
程式碼:
#include <stdio.h>
#include <string.h>
int r,c;
char a[1000][1000];
int d[8][2]={1,0,-1,0,0,1,0,-1,-1,-1,1,1,-1,1,1,-1};
void DFS(int i,int j)
{
a[i][j]='*';
for(int k=0;k<8;k++)
{
int x=i+d[k][0];
int y=j+d[k][1];
if(x>=0&&x<r&&y>=0&&y<c&&a[x][y]=='@')
DFS(x,y);
}
return ;
}
int main()
{
while(~scanf("%d%d",&r,&c)&&r)
{
for(int i=0;i<r;i++)
scanf("%s",a[i]);
int ans=0;
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
if(a[i][j]=='@')
{
DFS(i,j);
ans++;
}
}
printf("%d\n",ans);
}
return 0;
}