洛谷P7243 最大公约数

思路&题意:

为了方便理解,我们先画个图

在这里插入图片描述
现在就好理解了吧,以x,y为中心每一天就往外扩一层,求x,y=1时是第几天。
代码也是很好写的,只需要在BFS模板中加个__gcd函数求公约数就行了。

Code

#include <bits/stdc++.h>
#define ll long long
using namespace std;
struct point{
	long long x1,y1,step;
}start;
queue<point> dl;
const int N=3e3+5;
int n,m,sx,sy;
ll v[N][N];
ll a[N][N];
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};
int main(){
	cin >> n >> m;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cin >> a[i][j];
		}
	}
	cin >> sx >> sy;
	if(a[sx][sy]==1){
		cout<<0;
		return 0;
	}
	start.x1 = sx;
	start.y1 = sy;
	start.step = 1;
	v[start.x1][start.y1] = 1;
	dl.push(start);
	ll sum=a[sx][sy];
	while(!dl.empty()){
		point head = dl.front();
		dl.pop();
		for(int i=0;i<=3;i++){
			int tx=head.x1+dx[i];
			int ty=head.y1+dy[i];
			if(tx<1||tx>n||ty<1||ty>m||v[tx][ty]){
				continue;
			}
			v[tx][ty]=1;
			point temp;
			temp.x1 = tx;
			temp.y1 = ty;
			temp.step = head.step + 1;
			dl.push(temp);
			sum=__gcd(sum,a[tx][ty]);
			if(sum==1){
				cout<<head.step;
				return 0;
			}
		}
	}
	cout<<-1;
	return 0;
}
  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值