P4554 小明的游戏

小明的游戏

题目描述

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

输入格式

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

输出格式

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

样例 #1

样例输入 #1

2 2
@#
#@
0 0 1 1
2 2
@@
@#
0 1 1 0
0 0

样例输出 #1

2
0

提示

对于20%的数据满足: 1 ≤ n , m ≤ 10 1 \le n, m \le 10 1n,m10
对于40%的数据满足: 1 ≤ n , m ≤ 300 1 \le n, m \le 300 1n,m300
对于100%的数据满足: 1 ≤ n , m ≤ 500 1 \le n, m \le 500 1n,m500

code:

#include<iostream>
#include<deque>
#include<cstring>
using namespace std;
const int N=510;
typedef pair<int ,int >PII;
int n,m;
char g[N][N];
int x12,y12,x2,y2;
deque<PII>q;
int dist[N][N];
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};
int bfs(int x,int y){
    q.push_back({x,y});
    dist[x][y]=0;
    while(q.size()){
        auto t=q.front();
        q.pop_front();
        char ch=g[t.first][t.second];
        for(int i=0;i<4;i++){
            int a=t.first+dx[i];
            int b=t.second+dy[i];
            if(a<0||a>=n||b<0||b>=m) continue;
            if(dist[a][b]>=0) continue;
            if(g[a][b]==ch){
                dist[a][b]=dist[t.first][t.second];
                q.push_front({a,b});
            }
            if(g[a][b]!=ch){
                dist[a][b]=dist[t.first][t.second]+1;
                q.push_back({a,b});//bfs的二段性
            }
            if(a==x2&&b==y2) return dist[x2][y2];
        }
    }
    return -1;
}
int main(){
    while(cin>>n>>m,n||m){
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                cin>>g[i][j];
            }
        }
        memset(dist,-1,sizeof(dist));
        q.clear();//由于每次都是新的数组,所以要清空队列
        cin>>x12>>y12>>x2>>y2;
        int res=bfs(x12,y12);
        cout<<res<<endl;
    }
    return 0;
}
  • 40
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值