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

【传送门:BZOJ2464


简要题意:

  给出一个n*m的字符矩阵,给出起点和终点,每次移动只能上下左右移动,如果走到不同的字符需要1的花费,同种字符不需要花费

  求出从起点到终点的最少花费


题解:

  最短路水题(日常刷水,有益身心健康)


参考代码:

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
using namespace std;
int dx[5]={0,1,-1,0,0};
int dy[5]={0,0,0,-1,1};
char st[510][510];
int d[510][510];
bool v[510][510];
struct node
{
    int x,y;
}list[310000];
int main()
{
    int n,m;
    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);
        int sx,sy,ex,ey;
        scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
        sx++;sy++;ex++;ey++;
        list[1].x=sx;list[1].y=sy;
        memset(d,63,sizeof(d));d[sx][sy]=0;
        memset(v,false,sizeof(v));v[sx][sy]=true;
        int head=1,tail=2;
        while(head!=tail)
        {
            int x=list[head].x,y=list[head].y;
            for(int i=1;i<=4;i++)
            {
                int tx=x+dx[i],ty=y+dy[i];
                if(tx<1||ty<1||tx>n||ty>m) continue;
                int c;
                if(st[tx][ty]==st[x][y]) c=0;
                else c=1;
                if(d[tx][ty]>d[x][y]+c)
                {
                    d[tx][ty]=d[x][y]+c;
                    if(v[tx][ty]==false)
                    {
                        v[tx][ty]=true;
                        list[tail].x=tx,list[tail].y=ty;
                        tail++;if(tail==n*m+1) tail=1;
                    }
                }
            }
            head++;if(head==n*m+1) head=1;
            v[x][y]=false;
        }
        printf("%d\n",d[ex][ey]);
    }
    return 0;
}

 

posted @ 2018-03-16 13:50  Star_Feel  阅读(187)  评论(0编辑  收藏  举报