BFS模板

忘记具体是哪个题目的代码了贴出来当作模版记录一下
#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
int arr[25][25];//存储是否被访问的标志
char vis[25][25];//存放字符组
int num;
int H, L;//行,列
struct node {
	int x;
	int y;
};//用来存放坐标
int fx[] = { 1,0,0,-1 };
int fy[] = { 0,1,-1,0 };
bool pan(node temp) {//可以访问就返回true
	return (temp.x >= 0 && temp.x < H&& temp.y >= 0 && temp.y < L&& arr[temp.x][temp.y] == 0 && vis[temp.x][temp.y] == '.');
}

void BFS(int x, int y) {

	queue<node>Q;
	Q.push({ x, y });//将坐标存入队列

	while(!Q.empty()) {

		node A(Q.front());//用初始位置初始化A的坐标信息
		Q.pop();

		for (int i = 0; i < 4; ++i) {
			node temp;
			temp.x = A.x + fx[i];
			temp.y = A.y + fy[i];
			if (pan(temp)) {
				arr[temp.x][temp.y] = 1;
				++num;
				Q.push(temp);
			}
		}
	}

}

int main() {

	while (cin >> L >> H, H, L) {
		num = 0;
		memset(arr, 0, sizeof(arr));//初始化访问状态

		//输入字符
		for (int i = 0; i < H; ++i) {
			for (int j = 0; j < L; ++j) {
				cin >> vis[i][j];
			}
		}

		for (int i = 0; i < H; ++i) {
			for (int j = 0; j < L; ++j) {
				if (vis[i][j] == '@') {
					++num;
					BFS(i, j);//形参为行,列
				}
			}
		}
		cout << num << endl;

	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值