思路&题意:
为了方便理解,我们先画个图
现在就好理解了吧,以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;
}