题目
Time Limit: 1sec Memory Limit:256MB
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
There are multiple test cases. The first line contains an integer T, indicating the number of test cases.
Each test case begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. (0< m <= 100 and 0< 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 test case, 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.
Sample Input Copy
4
1 1
*
3 5
@@*
@
@@*
1 8
@@***@
5 5
****@
@@@
@**@
@@@@
@@**@
Sample Output Copy
0
1
2
2
Problem Source: Graph Algorithms
学习
/*
1008. Oil Deposits
遍历mat,mat[i][j] == '@',则dfs(i, j), ans ++;
dfs:直接转化为*,再dfs它的8个方向 。
类似于visited[i,j] = true,但是dfs的判断函数会变化为if(!visited(i,j) && mat[i][j] == '@')
注意dfs函数里面也有判断函数
坐标转化时,dir的设定很巧妙
*/
code
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
int rows, cols;
char mat[101][101];
int dir[8][2] = {1, 1, 0, 1, 1, 0, -1, -1, -1, 0, 0, -1, 1, -1, -1, 1};
void DFS(int, int);
int main()
{
int t;
cin >> t;
while(t--)
{
// memset(isVisited, false, sizeof(isVisited));
//输入
cin >> rows >> cols;
getchar();
for(int i = 1; i <= rows; ++i)
{
for(int j = 1; j <= cols; ++j)
{
cin >> mat[i][j];
}
getchar();
}
int kinds = 0;
for(int i = 1; i <= rows; ++i)
{
for(int j = 1; j <= cols; ++j)
if(mat[i][j] == '@')
{
kinds++;
DFS(i, j);
}
}
cout << kinds << endl;
}
return 0;
}
void DFS(int x, int y)
{
if(mat[x][y] == '@')
{
mat[x][y] = '*';
for(int i = 0; i < 8; ++i)
DFS(x + dir[i][0], y + dir[i][1]);
//8个方向,dir很巧妙
}
}