BZOJ2464: 中山市选[2009]小明的游戏

来源:互联网 发布:mysql to_date 编辑:程序博客网 时间:2024/05/01 08:10

Description

小明最近喜欢玩一个游戏。给定一个n * m的棋盘,上面有两种格子#和@。游戏的规则很简单:给定一个起始位置和一个目标位置,小明每一步能向上,下,左,右四个方向移动一格。如果移动到同一类型的格子,则费用是0,否则费用是1。请编程计算从起始位置移动到目标位置的最小花费。
Input

输入文件有多组数据。输入第一行包含两个整数n,m,分别表示棋盘的行数和列数。输入接下来的n行,每一行有m个格子(使用#或者@表示)。输入接下来一行有四个整数x1, y1, x2, y2,分别为起始位置和目标位置。

当输入n,m均为0时,表示输入结束。
Output

对于每组数据,输出从起始位置到目标位置的最小花费。每一组数据独占一行。

Sample Input

2 2

@#

#@

0 0 1 1

2 2

@@

@#

0 1 1 0

0 0

Sample Output

2

0

题目传送门
垃圾最短路
刚起床刷一刷垃圾题有益身心健康

#include<cmath>#include<cstdio>#include<cstring>#include<cstdlib>#include<algorithm>using namespace std;const int dx[4]={1,0,-1,0};const int dy[4]={0,1,0,-1};int n,m;int d[510][510];int head,tail;struct tt{int x,y;}list[2100000];bool v[510][510];int stx,sty,edx,edy;char st[510][510];void spfa(){    for(int i=1;i<=n;i++)        for(int j=1;j<=m;j++)            d[i][j]=999999;    d[stx][sty]=0;    memset(v,false,sizeof(v));v[stx][sty]=true;    head=1;tail=2;list[1].x=stx,list[1].y=sty;    while(head!=tail)    {        int x=list[head].x,y=list[head].y;        for(int i=0;i<4;i++)        {            int tx=x+dx[i],ty=y+dy[i];            if(tx<1||tx>n||ty<1||ty>m)continue;            int t=0;            if(st[tx][ty]!=st[x][y])t=1;            if(d[tx][ty]>d[x][y]+t)            {                d[tx][ty]=d[x][y]+t;                if(v[tx][ty]==false)                {                    v[tx][ty]=true;                    list[tail].x=tx,list[tail++].y=ty;                    if(tail==2100000)tail=1;                }            }        }        head++;        if(head==2000000+1)head=1;        v[x][y]=false;    }    printf("%d\n",d[edx][edy]);}int main(){    while(scanf("%d%d",&n,&m)!=EOF)    {        if(n==0&&m==0)break;        for(int i=1;i<=n;i++)            scanf("%s",st[i]+1);        scanf("%d%d%d%d",&stx,&sty,&edx,&edy);        stx++;sty++;edx++;edy++;        spfa();    }    return 0;}

by_lmy

阅读全文
0 0
原创粉丝点击