1. 程式人生 > 其它 >King's Path CodeForces - 242C

King's Path CodeForces - 242C

原題連結
考察:bfs
思路:
  可以移動的範圍不超過\(10^5\),所以直接bfs....

Code

#include <iostream>
#include <cstring>
#include <algorithm>
#include <map>
#include <queue>
#include <unordered_map>
using namespace std;
typedef pair<int,int> PII;
int n,sx,sy,dx,dy;
map<PII,int> um;
map<PII,bool> mp;
int xx[8] = {-1,-1,-1,0,0,1,1,1};
int yy[8] = {-1,0,1,-1,1,-1,0,1};
int bfs(int sx,int sy)
{
	queue<PII> q;
	q.push({sx,sy});
	while(q.size())
	{
		PII it = q.front();
		q.pop();
		int x = it.first,y = it.second;
		if(it.first==dx&&it.second==dy) return um[it];
		for(int i=0;i<8;i++)
		{
			int dx = x+xx[i],dy = y+yy[i];
			if(dx>0&&dy>0&&mp.count({dx,dy})&&!um.count({dx,dy}))
			{
				um[{dx,dy}] = um[it]+1;
				q.push({dx,dy});
			}
		}
	}
	return -1;
}
int main()
{
	scanf("%d%d%d%d%d",&sx,&sy,&dx,&dy,&n);
	for(int i=1;i<=n;i++)
	{
		int x,l,r;
		scanf("%d%d%d",&x,&l,&r);
		for(int j=l;j<=r;j++)
		  mp[{x,j}] = 1;
	}
  	printf("%d\n",bfs(sx,sy));
	return 0;
}