You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri, ai, bi (ai ≤ bi), denoting that cells in columns from number ai to numberbi inclusive in the ri-th row are allowed.
Your task is to find the minimum number of moves the king needs to get from square(x0, y0) to square (x1, y1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.
Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.
The first line contains four space-separated integers x0, y0, x1, y1 (1 ≤ x0, y0, x1, y1 ≤ 109), denoting the initial and the final positions of the king.
The second line contains a single integer n (1 ≤ n ≤ 105), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers ri, ai, bi (1 ≤ ri, ai, bi ≤ 109, ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in theri-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily.
It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 105.
If there is no path between the initial and final position along allowed cells, print -1.
Otherwise print a single integer — the minimum number of moves the king needs to get from the initial position to the final one.
5 7 6 11 3 5 3 8 6 7 11 5 2 5
4
3 4 3 10 3 3 1 4 4 5 9 3 10 10
6
1 1 2 10 2 1 1 3 2 6 10
-1
题意:现在有一个10^9 * 10^9的地图,给你两个点的坐标x1,y1 x2, y2 ,然后给你一个数字N,后面跟N行,每行的意思为:第一个数字r代表这个地图的行,后面的两个数字a,b为列,表示第r行从a-b列的地方可以走;国王可以走八个相邻的格子,问你最少多少步国王可以到达目的地,不能到达输出-1;
思路:BFS;因为地图很大不能开数组,所以想到用map+pair;用点对应步数即可,先把所有可以走的点都标记为-1,如果这个点存在且为-1才可以走。
#include <bits/stdc++.h>
using namespace std;
pair<int,int>now;
map<pair<int,int>,int> MAP;//点对应步数
int sx,sy,ex,ey,M;
int bfs()
{
int MOVE[8][2]={{1,1},{1,-1},{-1,1},{-1,-1},{0,1},{1,0},{-1,0},{0,-1}};//八个方向
queue<pair<int,int> >q;
now.first=sx; now.second=sy; MAP[now]=0;
q.push(now);
while(!q.empty())
{
now=q.front();
q.pop();
if(now.first == ex && now.second == ey) return MAP[now];
for(int i=0;i<8;i++)
{
pair<int,int> next;
next.first=now.first+MOVE[i][0];next.second=now.second+MOVE[i][1];
if(MAP.count(next)&&MAP[next]==-1)//这个点可以走且没走过
{
MAP[next]=MAP[now]+1;
q.push(next);
}
}
}
return -1;
}
int main()
{
while(cin>>sx>>sy>>ex>>ey)
{
MAP.clear();
cin>>M;
int l,a,b;
while(M--)
{
cin>>l>>a>>b;
for(int i=a;i<=b;i++)
{
now.first=l; now.second=i;
MAP[now]=-1;//将这些点放入MAP,初始化为-1表示能走
}
}
if(!MAP.count(make_pair(ex, ey))) cout << -1 << endl;//终点没法走
else cout << bfs() << endl;
}
}