您的位置:首页 > 其它

codeforces 242C map记录+BFS

2014-03-20 23:29 316 查看
/*
题意:一个棋盘有的点可以走,有的点不能走,求从起点到终点最少要多少
步,假如无法走到则输出-1.

思路:普通的暴力BFS,由于图是10^9*10^9,所以要用到map来记录图。
*/
#include <cstdio>
#include <map>
#include <queue>

using namespace std;

int main(void)
{
int x0,y0,x1,y1,n,r,a,b;
map<int,map<int,int>>m;
while (scanf("%d%d%d%d%d",&x0,&y0,&x1,&y1,&n) == 5)
{
while (n--)
{
scanf("%d%d%d",&r,&a,&b);
for(int i=a; i<=b; i++)
m[r][i] = -1;
}
queue<int>q;
q.push(x0);
q.push(y0);
q.push(0);
int ans = -1;//无法走通则ans为-1
while (!q.empty())//BFS
{
int x = q.front();
q.pop();
int y = q.front();
q.pop();
int step = q.front();
q.pop();
if (x==x1 && y==y1)
{
ans = step;//step记录到该点需走多少步
break;
}
for(int i=-1; i<=1; i++)
for(int j=-1; j<=1; j++)
{
if (i==0 && j==0)
continue;
int cx = x+i;
int cy = y+j;
if (m[cx][cy] == -1)
{
m[cx][cy] = 1;
q.push(cx);
q.push(cy);
q.push(step+1);
}
}
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: