codeforces 242C map记录+BFS

/*
题意:一个棋盘有的点可以走,有的点不能走,求从起点到终点最少要多少
步,假如无法走到则输出-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;
}

 

posted @ 2014-03-20 23:29  辛力啤  阅读(226)  评论(0编辑  收藏  举报