(2021-5)搜索类题目(bfs dfs)-计算水洼数量 c++

2021/5/10 22:29:05

本文主要是介绍(2021-5)搜索类题目(bfs dfs)-计算水洼数量 c++,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

题目描述

题目:有一块N*M的土地,下雨后积起了雨水,有水的区域标记为"w",干燥标记为".",8连通区域被认为是连接在一起的;请求出院子里有多少水洼?

input

w w w . 
. . . .
. . w w
w w . .

output

2

思路:

  • 对于8连通区域在搜索时,搜索时设置8个方向;
  • 'w'进行一次搜索;搜索完毕后被搜索的'w'所在的连通区域都被标记为访问过
  • 一个连通区域搜索完毕之后水洼的数量加一
  • 搜索算法使用bfs或dfs

代码如下:

#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

struct node{
	int x, y;
}Node;

int num = 0;
char plot[4][4]; //存放地图
int vis[4][4]; // 标记是否访问过
int dir[8][2] = {{0,1},{0,-1},{1,0},{-1,0},{-1,1},{-1,-1},{1,1},{1,-1}}; //8个方向


void bfs(int x, int y){
	queue <node> Q;
	Node.x = x;
	Node.y = y;
	Q.push(Node);
	while(!Q.empty()){
		Node = Q.front();
		Q.pop();
		for(int i=0; i<8; i++){
			int newX = Node.x + dir[i][0];
			int newY = Node.y + dir[i][1];
			if(newX>=0 && newX <4 && newY>=0 && newY<4 && plot[newX][newY] =='w' && !vis[newX][newY]){
				Node.x = newX;
				Node.y = newY;
				Q.push(Node);
				vis[newX][newY] = true;
			}
		}
	}
}

void dfs(int x, int y){
	vis[x][y] = true;
	for(int i=0; i<8; i++){
		int newX = x + dir[i][0];
		int newY = y + dir[i][1];
		if(newX>=0 && newX <4 && newY>=0 && newY<4 && plot[newX][newY] =='w' && !vis[newX][newY]){
			dfs(newX, newY);
		}
	}
}

int main(){
	memset(vis, 0, sizeof(vis));
	for(int i=0; i<4; i++){
		for(int j=0; j<4; j++){
			cin >> plot[i][j];
		}
	} //数组初始化

	for(int i=0; i<4; i++){
		for(int j=0; j<4; j++){
			if(plot[i][j] == '.' || vis[i][j]) continue; //如果元素被访问过或者位干燥区域,则直接过滤掉
			bfs(i, j);
			num++;
		}
	}
	printf("%d\n", num);
	return 0;
}

运行结果
在这里插入图片描述



这篇关于(2021-5)搜索类题目(bfs dfs)-计算水洼数量 c++的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程