| Time Limit: 2000MS | Memory Limit: 65536KB | 64bit IO Format: %lld & %llu |
Description
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
大致题意:给出一个图找出一共多少块油田。油田用‘@’表示,与它相邻的8个区域如果还有油田‘@’则视为一块。
dfs+邻接矩阵。入门的dfs,代码:
#include <iostream>
#include<cstdio>
using namespace std;
int n,m;
const int maxn=105;
char grid[maxn][maxn];
int dir[8][2]={
{-1,-1},{-1,0},
{-1,1},{0,-1},
{0,1},{1,-1},
{1,0},{1,1}
};//一个点有八个方向,都要遍历。坐标作为界限判断
void dfs(int x,int y)
{
int a,b,i;
grid[x][y]='*';//若访问到,标记为’*‘,表示联通,防止重复访问
for(i=0;i<8;i++)
{
a=x+dir[i][0];//更新x坐标
b=y+dir[i][1];//更新y坐标
if(a>=0&&a<m&&b>=0&&b<n&&grid[a][b]=='@') dfs(a,b);
}
}
int main()
{
int i,j;
while(scanf("%d%d",&m,&n)!=EOF&&m!=0)
{
int ans=0;
for(i=0;i<m;i++)
scanf("%s",grid[i]);//不用两重循环,%s
for(i=0;i<m;i++)
for(j=0;j<n;j++)
if(grid[i][j]=='@')
{
dfs(i,j);
ans++;
}
printf("%d\n",ans);
}
return 0;
}
本文介绍了一种使用深度优先搜索(DFS)算法结合邻接矩阵来解决油田探测问题的方法。任务是确定给定网格中独立油田的数量,其中每个油田由相邻的油井组成。通过递归地探索所有可能的邻接点来实现这一目标。
195

被折叠的 条评论
为什么被折叠?



