求助,BFS,TLE了,P1443
查看原帖
求助,BFS,TLE了,P1443
555073
Lizzycoder楼主2022/6/16 19:56

BFS; 不知道为什么就TLE了

#include<bits/stdc++.h>
using namespace std;
struct point
{
	int x,y,step;
}q[40010],s,d;
int f = 1,e = 1;
bool used[10010][10010];
int dx[8] = {1,1,-1,-1,2,2,-2,-2};
int dy[8] = {2,-2,2,-2,1,-1,-1,1};
int n,m,x,y;
int bfs()
{
	f = 1,e = 1;
	q[f] = s;
	if(x == d.x && y == d.y)
	{
		return 0;
	}
	while(f < e)
	{
		point u = q[f++];
		point v;
		for(int i = 0;i < 8;i++)
		{
			v.x = u.x + dx[i],v.y = u.y + dy[i],v.step = u.step + 1;
			if(v.x < 1 || v.x > n || v.y < 1||v.y > m) continue;
			if(v.x == d.x && v.y == d.y)
			{
				return v.step;
			}
			if(used[v.x][v.y] == 1)                    continue;
			q[++e] = v;
			used[v.x][v.y] = 1;
		}
	}
	return -1;
}
int main()
{
	cin >> n >> m >> x >> y;
	for(int i = 1;i <= n;i ++)
	{
		for(int j = 1;j <= m;j++)
		{
			s.x = x,s.y = y,s.step = 0;
			memset(used,0,sizeof(used));
			used[s.x][s.y] = 1;
			d.x = i,d.y = j;
			printf("%-5d",bfs());
		}
		cout<<endl;
	 } 
	return 0;
}

#include<bits/stdc++.h> using namespace std; struct point { int x,y,step; }q[40010],s,d; int f = 1,e = 1; bool used[10010][10010]; int dx[8] = {1,1,-1,-1,2,2,-2,-2}; int dy[8] = {2,-2,2,-2,1,-1,-1,1}; int n,m,x,y; int bfs() { f = 1,e = 1; q[f] = s; if(x == d.x && y == d.y) { return 0; } while(f < e) { point u = q[f++]; point v; for(int i = 0;i < 8;i++) { v.x = u.x + dx[i],v.y = u.y + dy[i],v.step = u.step + 1; if(v.x < 1 || v.x > n || v.y < 1||v.y > m) continue; if(v.x == d.x && v.y == d.y) { return v.step; } if(used[v.x][v.y] == 1) continue; q[++e] = v; used[v.x][v.y] = 1; } } return -1; } int main() { cin >> n >> m >> x >> y; for(int i = 1;i <= n;i ++) { for(int j = 1;j <= m;j++) { s.x = x,s.y = y,s.step = 0; memset(used,0,sizeof(used)); used[s.x][s.y] = 1; d.x = i,d.y = j; printf("%-5d",bfs()); } cout<<endl; } return 0; }

2022/6/16 19:56
加载中...