看了一下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 })