Hoj 1140 The Game

来源:互联网 发布:剑灵刺客捏脸数据导入 编辑:程序博客网 时间:2024/04/29 03:48

题目连接:http://acm.hit.edu.cn/hoj/problem/view?id=1140

题意:求从起点到终点的最少的转弯数.即折线数目。

可以用BFS来做,对于不同的是,dist的求法,加一层while循环判断是否在同一方向上前进,在此方向上的点的dist都是相同的。

#include <iostream>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <math.h>#include <algorithm>#include <stack>#include <queue>using namespace std;struct Point{    int x;    int y;};int map[100][100];int dist[100][100];int vis[100][100];int disx[4] = {-1,0,1,0};int disy[4] = {0,1,0,-1};int startx;int starty;int endx;int endy;int w,h;void bfs(){    queue<Point> q;    Point temp,nex,s;    s.x = startx;    s.y = starty;    q.push(s);    vis[s.x][s.y] = 1;    while(!q.empty())    {        temp = q.front();        q.pop();        if(temp.x == endx && temp.y == endy)        {            break;        }        for(int i=0; i<4; i++)        {            int tempx = temp.x + disx[i];            int tempy = temp.y + disy[i];            while(tempx>=0 && tempx<h && tempy>=0 && tempy<w && vis[tempx][tempy] == 0 && map[tempx][tempy] == 0)            {                nex.x = tempx;                nex.y = tempy;                vis[tempx][tempy] = 1;                q.push(nex);                dist[tempx][tempy] = dist[temp.x][temp.y] + 1;                tempx += disx[i];                tempy += disy[i];            }        }    }}int main(){#ifndef ONLINE_JUDGE    freopen("in.txt","r",stdin);#endif    int caseN = 0;    while(scanf(" %d %d",&w,&h)!=EOF)    {         memset(map,0,sizeof(map));        caseN++;        if(w == 0 && h == 0)        {            break;        }        char c;        for(int i=1; i<=h; i++)        {            getchar();            for(int j=1; j<=w; j++)            {                scanf("%c",&c);                if(c == 'X')                {                    map[i][j] = 1;//X是1,空格是0                }            }        }        h+=2;        w+=2;        int x1,y1;        int x2,y2;        printf("Board #%d:\n",caseN);        int caseM = 0;        while(scanf(" %d %d %d %d",&y1,&x1,&y2,&x2)!=EOF)        {            if(x1==0 && y1==0 && y2==0 && x2 == 0)            {                break;            }            memset(vis,0,sizeof(vis));            memset(dist,0,sizeof(dist));            caseM++;            startx = x1;            starty = y1;            endx = x2;            endy = y2;            map[x2][y2] = 0;//先把它置为空格            bfs();            int ans = dist[x2][y2];            if(ans!=0)                printf("Pair %d: %d segments.\n",caseM,ans);            else                printf("Pair %d: impossible.\n",caseM);            map[x2][y2] = 1;//还原        }        printf("\n");    }    return 0;}