WAP面试题——BFS解法

看了一下BFS算法,想到之前works application 的试题“Orienteering”,于是重新利用BFS算法做了一遍。虽然知道了BFS算法的思想,但要灵活运用还真没那么简单,容易考虑不周全,或者不知道何从下手。还是需要多练习。

题目大概意思是这样:

S-开始位置

G-目标位置

#-不能通过的障碍

要从S到G,把所有的@“吃到”,求出最少的步数。


代码如下:

#include<iostream>
#include<vector>
#include<algorithm>
#include<stdexcept>
#include<queue>
using namespace std;


class Orienteering{
public:
	Orienteering():checkpoint(0),map(NULL){
		mv = new int*[4];
		for (int i = 0; i < 4; ++i)
			mv[i] = new int[2];
		mv[0][0] = mv[2][1] = -1;
		mv[1][0] = mv[3][1] = 1;
		mv[2][0] = mv[3][0] = mv[0][1] = mv[1][1] = 0;
	}
	class Point{
	public:
		int x, y;
		bool operator==(const Point& pt){
			return x == pt.x&&y == pt.y;
		}
	};
	class State{
	public:
		int x;
		int y;
		int step;
		vector<Point> vp;
	};
	struct Ck{
		int check, step;
	};
	Ck** check;
	queue<State> temp;
	void main();
	int bfs(State state);
	int checkpoint;
	int w, h;//宽和高
	int sx, sy;//start位置  x-h
	int dx, dy;//goal 位置
	char** map;
	int** mv;
};

int Orienteering::bfs(State state){
	while (!temp.empty()){
		State S = temp.front();
		if (checkpoint == check[dx][dy].check&&S.x==dx&&S.y==dy)
			return S.step;
		temp.pop();
		for (int i = 0; i < 4; ++i){
			State s = S;
			if ((s.x + mv[i][0]) >= 0 && (s.x + mv[i][0]) < h
				&& (s.y + mv[i][1] >= 0) && (s.y + mv[i][1] < w)
				&& map[s.x + mv[i][0]][s.y + mv[i][1]] != '#'){
				s.x += mv[i][0];
				s.y += mv[i][1];
				++s.step;
				if (map[s.x][s.y] == '@'){//如果遇到@
					if (find(s.vp.begin(), s.vp.end(), Point{ s.x, s.y }) == s.vp.end()){//新的@
						s.vp.push_back({ s.x, s.y })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值