Enmin @ 2024-08-08 16:27:10
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using db = double;
using str = string;
const int N = 1e7;
const int M = 1e4;
//升:priority_queue <int,vector<int>,greater<int>> qe;
//降:priority_queque <int,vector<int>,less<int>> qe;
int g[9] = {0,-2,-1,1,2,2,1,-1,-2};
int h[9] = {0,1,2,2,1,-1,-2,-2,-1};
int n,m,l,r,sum=1,tail=1,x[N],y[N],z[N];
int bfs(int xy,int yx) {
bool b[M][M];
x[1]=l;
y[1]=r;
z[1]=0;
b[l][r]=1;
if(l==xy&&r==yx) {
return 0;
}
while(sum<=tail) {
for(int k=1;k<=8;k++) {
int t1 = x[sum] + g[k];
int t2 = y[sum] + h[k];
if(t1>0&&t1<=n&&t2>0&&t2<=m&&b[t1][t2]==0) {
b[t1][t2]=1;
tail++;
x[tail]=t1;
y[tail]=t2;
z[tail]=z[sum]+1;
if(t1==xy&&t2==yx) {
return z[tail];
}
}
}
sum++;
}
return -1;
}
int main() {
scanf("%d%d%d%d",&n,&m,&l,&r);
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
int ans=0;
ans=bfs(i,j);
printf("%d",ans);
sum=1,tail=1;
if(j!=m) {
printf(" ");
}else {
printf("\n");
}
}
}
return 0;
}
我用的是sublime Text的编程程序。 我电脑输出样例时输出了这个玩意儿:
bash: 第 2 行: 13681 段错误
by Enmin @ 2024-08-08 16:28:57
是输入样例,不是输出......字都能打错我无语
by Enmin @ 2024-08-08 16:30:57
真AC!!!
by Enmin @ 2024-08-08 16:33:32
我这是BFS,别看错了。
by Wilson_Lee @ 2024-08-08 16:34:50
@Enmin 所以为什么数组开那么大呢?
by Enmin @ 2024-08-08 16:37:41
数组开小了,还是:
bash: 第 2 行: 13681 段错误
by Enmin @ 2024-08-08 16:38:13
@Wilson_Lee
by Enmin @ 2024-08-08 16:43:43
等等,额......刚刚没有开很小
by Enmin @ 2024-08-08 16:44:45
@Wilson_Lee 谢谢!!!!!!!!!!!已解决:
bash: 第 2 行: 13681 段错误
by Enmin @ 2024-08-08 16:47:07
@Wilson_Lee 已关
by Wilson_Lee @ 2024-08-08 16:49:12
#include<bits/stdc++.h>
using namespace std;
#define ll long long;
#define db double;
#define str string;
const int N = 160005;
const int M = 405;
//升:priority_queue <int,vector<int>,greater<int>> qe;
//降:priority_queque <int,vector<int>,less<int>> qe;
int g[9] = {0,-2,-1,1,2,2,1,-1,-2};
int h[9] = {0,1,2,2,1,-1,-2,-2,-1};
int n,m,l,r,sum=1,tail=1,x[N],y[N],z[N];
bool b[M][M];
int bfs(int xy,int yx) {
memset(b,0,sizeof(b));
x[1]=l;
y[1]=r;
z[1]=0;
b[l][r]=1;
if(l==xy&&r==yx) {
return 0;
}
while(sum<=tail) {
for(int k=1;k<=8;k++) {
int t1 = x[sum] + g[k];
int t2 = y[sum] + h[k];
if(t1>0&&t1<=n&&t2>0&&t2<=m&&b[t1][t2]==0) {
b[t1][t2]=1;
tail++;
x[tail]=t1;
y[tail]=t2;
z[tail]=z[sum]+1;
if(t1==xy&&t2==yx) {
return z[tail];
}
}
}
sum++;
}
return -1;
}
int main() {
scanf("%d%d%d%d",&n,&m,&l,&r);
for(int i=1;i<=n;i++) {
for(int j=1;j<=m;j++) {
int ans=0;
ans=bfs(i,j);
printf("%d",ans);
sum=1,tail=1;
if(j!=m) {
printf(" ");
}else {
printf("\n");
}
}
}
return 0;
}
@Enmin 帮你改到90分了,T的那个点应该是bfs要优化一下