二维矩阵内的BFS搜索

1.混境之地1 - 蓝桥云课 (lanqiao.cn)

题目解读

在思考的时候觉得传送门是个很玄幻的东西,在行走的路径上简直有无数种排列组合,我刚开始还想着怎么排列组合出来。

后来发现,,,怎么可能是自己来排列组合,用BFS跑一遍整个矩阵。。。到达每个点,除了上下左右四个方向,如果是到了一个传送门的启动点,更新一下它的传送点的最小距离。遍历过程中,若存在一个方案使得到达的点的距离更小,则更新距离并将该点入队,更新其他点。

问题还来到了,如何知道一个点是不是传送门的启动点。由于题目说一个点只能是一个门的启动点,所以可以用两个矩阵来存储和查找传送门的信息。

优化

使用Djikstra算法进行优化,确保每个点一经确定便不用再更新,使用优先队列实现。

#include <iostream>
#include <map>
#include <utility>
#include <queue>
#include <cstring>
using namespace std;

/*struct node{
  int x,y,p;
};*/
/*struct xy{
	int x,y;
	operator < (const xy &u)const {
		if(x==u.x){
			return y < u.y;
		}
		else return x < u.x;
	}
};*/

int n,m;
int a,b,c,d;
char g[55][55];
int k;
//map<xy,node> mm;
int pp[55][55];
pair<int,int> xy[55][55];
int E;
int l[55][55];
int xt[4] = {-1,1,0,0};
int yt[4] = {0,0,-1,1};


void bfs(){
  queue<pair<int,int>> q;
  l[a][b] = 0;
  q.push({a,b});
  while(!q.empty()){
    auto t = q.front();
    //cout << t.first << ' ' << t.second << '\n';
    q.pop();
    if(pp[t.first][t.second]){
          int xf = xy[t.first][t.second].first;
          int yf = xy[t.first][t.second].second;
          if(l[t.first][t.second] + pp[t.first][t.second] < l[xf][yf]){
            l[xf][yf] = l[t.first][t.second] + pp[t.first][t.second];
            q.push({xf,yf});
            //if(xf==1 && yf == 5) cout << l[xf][yf] << "=\n";
          }
        }
    for(int i=0 ; i < 4 ; i++){
      int xx = t.first + xt[i];
      int yy = t.second + yt[i];
      if(xx <= n && xx >= 1 && yy >= 1 && yy <= m && g[xx][yy]!= '#'){
        //xy tt = {xx,yy};
        if(l[t.first][t.second] + 1 < l[xx][yy]){
            l[xx][yy] = l[t.first][t.second] + 1;
            q.push({xx,yy});
            //if(xx==1 && yy == 5) cout << l[xx][yy] << "=\n";
        }
        
      }
    }
  }
  return ;
}



int main()
{
  cin >> n >> m;
  cin >> a >> b >> c >> d;
  for(int i = 1 ; i<=n ; i++){
    for(int j = 1 ; j <= m ; j++){
      cin >> g[i][j];
    }
  }
  cin >> k;
  cout << k << '\n';
  for(int i = 1 ; i <= k ; i++){
    int x1,y1,x2,y2,p;
    cin >> x1 >> y1 >> x2 >> y2 >> p;
    //mm[{x1,y1}] = {x2,y2,p};
    pp[x1][y1] = p;
    xy[x1][y1] = {x2,y2};
    //cout << "-------\n";
  }
  cin >> E;
  memset(l,0x3f,sizeof(l));
  bfs();
  //cout << "=========\n";
  
  /*for(int i = 1 ; i<=n ; i++){
    for(int j = 1 ; j <= m ; j++){
      cout << l[i][j] << ' ';
    }
    cout << '\n';
  }*/
  
  if(l[c][d] > E) {
    cout << -1;
  }
  else {
    cout << E - l[c][d];
  }

  return 0;
}

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值