P2802 回家(BFS)C++

P2802 回家

在这里插入图片描述
输入输出样例
输入

3 3
2 1 1
1 1 0
1 1 3

输出

4

参考的是某个博主的思路
在这里插入图片描述

#include<iostream>
#include<stdio.h>
#include<iomanip>
#include<stack>
#include<queue>
#include<cstdlib>
#include <algorithm>
#include<string.h>
#include<math.h>
#define llu unsigned long long
using namespace std;

int a[15][15]={
    
    0};//构造地图 
int vis[15][15]={
    
    0}; //记录该点的血量 
int dir[4][2] = {
    
     {
    
    0,1},{
    
    0,-1},{
    
    1,0},{
    
    -1,0} };
bool flag=false;
struct node{
    
    
	int dx,dy,step,hp;
}ans,t;
queue<node> q;

void bfs(int n,int m)
{
    
    
	while(!q.empty()&&!flag)
	{
    
    
		t=q.front();
		q.pop();
		if(t.hp==1)continue;//hp=1了,已经没戏了,这次就跳过去吧; 
		for(int i=0;i<4&&!flag;i++)
		{
    
    
			if(a[t.dx+dir[i][0]][t.dy+dir[i][1]])//这个点不是障碍物
				if(vis[t.dx+dir[i][0]][t.dy+dir[i][1]]<t.hp-1)//如果血量更大,可以试试 
				{
    
    
					ans.dx = t.dx+dir[i][0];
					ans.dy = t.dy+dir[i][1];
					ans.step=t.step+1;
					ans.hp = a[ans.dx][ans.dy]==4?6:t.hp-1;
					vis[ans.dx][ans.dy]=ans.hp;
					if(a[ans.dx][ans.dy]==3)flag=true;
					q.push(ans);
				}
		}
	}
}


int main()
{
    
    
	int n,m,ax,ay;
	cin >> n >> m ;
	for(int i=1;i<=n;i++)
	{
    
    
		for(int j=1;j<=m;j++)
		{
    
    
			cin >> a[i][j] ;
			if(a[i][j]==2) 
				ax=i,ay=j;
		}
	}
			
	/*for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cout << a[i][j] << " ";
		}
		cout << endl ;
	}*/
	
	q.push(node({
    
    ax,ay,0,6}));
	vis[ax][ay]=6;
	bfs(n,m);
	if(flag)cout << ans.step << endl ;
	else cout << "-1" << endl ;
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wangyurenwls/article/details/118724737
今日推荐