#P2960 [USACO09OCT]Invasion of the Milkweed G题解

原题跳转

这是一道bfs的题。标记出不能走的方格,一点一点往下递归,每次更新答案(时间)即可。 需要注意的地方已经在代码中标出。

参考代码

#include <iostream>
#include <queue>
using namespace std;

struct node {
	int x,y,tm;
};
int dx[8]={1,0,-1,0,1,1,-1,-1},dy[8]={0,1,0,-1,-1,1,1,-1};//8个坐标提前预设好,bfs方便往前推 
int ans; 
char a[105][105];
queue<node> myq;
void bfs(){
	while (!myq.empty()){//没有推到边界就继续推 
		node t = myq.front(); 
		myq.pop();
		ans = t.tm;
		for (int i = 0; i < 8; i++) {//8个方向进行枚举 
			int x = t.x + dx[i];
			int y = t.y + dy[i];
			if (a[x][y] == '.') {
				a[x][y] = '*';
				myq.push({x,y,t.tm+1});//如果符合条件,就把下一层的数据压进队列 
			}
		}
	}
}

int main() {
	int n,m,sx,sy;
	cin>>m>>n>>sy>>sx;//注意先输入列,后输入行 
	for (int i=1;i<=n;i++){
		for (int j=1;j<=m;j++)
			cin >> a[i][j];
	}
	myq.push({n-sx+1,sy,0});//(1,1)定义为左下角,所以x轴坐标要用(n-sx+1) 
	a[n-sx+1][sy]='*';
	bfs();
	cout<<ans<<endl;
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值