图的dfs+bfs(2021-08-04)

A-Oil Deposits

题意: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.

输入: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.

输出: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.
(注:即油田周围一圈8个点,如果有油,则油量相同)
样例:
Sample Input:
1 1
*
3 5
@@*
@
@@*
1 8
@@***@
5 5
****@
@@@
@**@
@@@
@
@@**@
0 0

Sample Output
0
1
2
2

思路(查):利用广度优先搜索(bfs),寻找一个油田周围紧邻的油田,如果找到则此部分连通图全置为vis=1, 找几次’@'则证明有几个油量不同的油田

俩种方法:(1)标记数组 (2)访问过的点改为’*’

#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
const int maxn=1e2+5;
int n,m;
char map[maxn][maxn];
bool vis[maxn][maxn];//标记数组:标记是否被访问 
struct Node{
	int x;
	int y;
}; 
int dx[8]={0,1,1,1,0,-1,-1,-1};
int dy[8]={-1,-1,0,1,1,1,0,-1};
void bfs(Node node_){
	queue<Node> q;
	vis[node_.x][node_.y]=true;
	q.push(node_);
	Node tmp,next;
	while(!q.empty()){
		tmp=q.front();
		q.pop();
		for(int i=0;i<8;i++){
			next.x=tmp.x+dx[i];
			next.y=tmp.y+dy[i];
		if(next.x>=n||next.x<0||next.y<0||next.y>=m||map[next.x][next.y]=='*'){
			continue;
		}
		if(vis[next.x][next.y]==false){
			vis[next.x][next.y]=true;
			q.push(next);	
		}
		}
	}
	
}
int main(){
	while(cin>>n>>m&&n&&m){
		memset(vis,0,sizeof(vis));
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				cin>>map[i][j];
			}
		}
		int ret=0; 
		Node tmp;
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				if(map[i][j]=='@'&&vis[i][j]==false){
					
					tmp.x=i;
					tmp.y=j;
					//这里创造一个结构体,来储存该节点下标位置 
					bfs(tmp);
					ret++;
				}
			
			}
		}
		cout<<ret<<endl;
		
	}
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值