C/C++教程

P2802 回家(BFS)C++

本文主要是介绍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;
}

这篇关于P2802 回家(BFS)C++的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!