I have some C++ code I wrote to find an A* path, but it's behaving strangely. There's quite a bit of code here, so I'll split it into chunks and try to explain what I'm doing. I'm not gonna explain how A* pathing works. I assume if you're trying to help you already know the algorithm.
First off, here's my function for calculating the h value of a node:
int
calculateH(int cX, int cY, int eX, int eY, int horiCost = 10, int diagCost = 14) {
int h;
int xDist = abs(eX - cX);
int yDist = abs(eY - cY);
if (xDist > yDist)
h = (diagCost * yDist) + (horiCost * (xDist - yDist));
else
h = (diagCost * xDist) + (horiCost * (yDist - xDist));
return h;
}
I'm pretty sure there's no problem here; pretty simple stuff.
Next my Node class. And I know, I know, make those variables private and use getters; I just did it this way for testing purposes.
class Node {
public:
Node(int x_, int y_, int g_, int h_, int pX_, int pY_, bool list_) {
x = x_;
y = y_;
g = g_;
h = h_;
pX = pX_;
pY = pY_;
list = list_;
};
int x, y, g, h, pX, pY;
bool list;
};
Each Node has an X and Y variable. I only store G and H, not F, and calculate F when I need it (which is only once in my code). Then there's the Parent X and Y values. List is a boolean: fale = open list, true = closed list.
I also have a Object class. The only variables that matter here are X, Y, and Passable, all accessed through getters.
Now here's the start of my actual pathfinding code. It returns a string of numbers corresponding to directions as shown below:
432
501
678
So 1 means move right, 8 means go down and right, 0 means don't go anywhere.
string
findPath(int startX, int startY, int finishX, int finishY) {
// Check if we're already there.
if (startX == finishX && startY == finishY)
return "0";
// Check if the space is occupied.
for (int k = 0; k < objects.size(); k ++)
if ((objects[k] -> getX() == finishX) &&
(objects[k] -> getY() == finishY) &&
(!objects[k] -> canPass()))
return "0";
// The string that contains our path.
string path = "";
// The identifier of the current node.
int currentNode = 0;
// The list of nodes.
vector<Node> nodes;
// Add the starting node to the closed list.
nodes.push_back(Node(startX, startY, 0,
calculateH(startX, startY, finishX, finishY),
startX, startY, true));
Now we loop through until we find the destination. Note that sizeLimit is just to make sure we don't loop forever (it WONT if I can fix this code. As of right now it's very necessary). Everything from this point on, until I mark otherwise, is inside the i j loops.
int sizeLimit = 0;
while ((nodes[currentNode].x != finishX) | (nodes[currentNode].y != finishY)) {
// Check the surrounding spaces.
for (int i = -1; i <= 1; i ++) {
for (int j = -1; j <= 1; j ++) {
bool isEmpty = true;
// Check if there's a wall there.
for (int k = 0; k < objects.size(); k ++) {
if ((objects[k] -> getX() == (nodes[currentNode].x + i)) &&
(objects[k] -> getY() == (nodes[currentNode].y + j)) &&
(!objects[k] -> canPass())) {
isEmpty = false;
}
}
Next part:
// Check if it's on the closed list.
for (int k = 0; k < nodes.size(); k ++) {
if ((nodes[k].x == (nodes[currentNode].x + i)) &&
(nodes[k].y == (nodes[currentNode].y + j)) &&
(nodes[k].list)) {
isEmpty = false;
}
}
Continuing on:
// Check if it's on the open list.
for (int k = 0; k < nodes.size(); k ++) {
if ((nodes[k].x == (nodes[currentNode].x + i)) &&
(nodes[k].y == (nodes[currentNode].y + j)) &&
(!nodes[k].list)) {
// Check if the G score is lower from here.
if (nodes[currentNode].g + 10 + (abs(i * j) * 4) <= nodes[k].g) {
nodes[k].g = nodes[currentNode].g + 10 + (abs(i * j) * 4);
nodes[k].pX = nodes[currentNode].x;
nodes[k].pY = nodes[currentNode].y;
}
isEmpty = false;
}
}
This is the last part of the i j loop:
if (isEmpty) {
nodes.push_back(Node(nodes[currentNode].x + i,
nodes[currentNode].y + j,
nodes[currentNode].g + 10 + (abs(i * j) * 4),
calculateH(nodes[currentNode].x + i, nodes[currentNode].y + j, finishX, finishY),
nodes[currentNode].x,
nodes[currentNode].y,
false));
}
}
}
Now we find the Node with the lowest F score, change it to the current node, and add it to the closed list. The protection against infinite lopping is also finished up here:
// Set the current node to the one with the lowest F score.
int lowestF = (nodes[currentNode].g + nodes[currentNode].h);
int lowestFIndex = currentNode;
for (int k = 0; k < nodes.size(); k ++) {
if (((nodes[k].g + nodes[k].h) <= lowestF) &&
(!nodes[k].list)) {
lowestF = (nodes[k].g + nodes[k].h);
lowestFIndex = k;
}
}
currentNode = lowestFIndex;
// Change it to the closed list.
nodes[currentNode].list = true;
sizeLimit ++;
if (sizeLimit > 1000)
return "";
}
The problem I'm having is that it wont find certain paths. It seems to never work if the path goes up or left at any point. Down, left, and right all work fine. Most of the time anyway. I have absolutely no idea what's causing this problem; at one point I even tried manually following my code to see where the problem was. No surprise that didn't work.
And one more thing: if you're counting my curly braces (first of all wow, you have more dedication than I thought), you'll notice I'm missing a close brace at the end. Not to mention my return statement. There's a little bit of code at the end to actually make the path that I've left out. I know that that part's not the problem however; I currently have it commented out and it still doesn't work in the same way. I added some code to tell me where it's not working, and it's at the pathfinding part, not the interpretation.
Sorry my code's so messy and inefficient. I'm new to c++, so any critical advice on my technique is welcome as well.
I think that when you are looking for the next "currentNode", you should not start with lowestF = (nodes[currentNode].g + nodes[currentNode].h); because that value, in principle, will (always) be lower-or-equal-to any other nodes in the open-set. Just start with the value of std::numeric_limits<int>::max() or some very large number, or use a priority queue instead of an std::vector to store the nodes (like std::priority_queue, or boost::d_ary_heap_indirect).
I'm pretty sure that is the problem. And since your heuristic can very often be equal to the actual path-distance obtained, there is a good chance that following nodes in the open-set turn out to have the same cost (g+h) as the currentNode. This would explain why certain paths get explored and others don't and why it gets stuck.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I've been trying to implement A* for weeks so an enemy can chase a player in my game, and I can't get it to work. I've been working on it the entire weekend, and I even ended up scraping most of it and re writing it. I can draw a path from the starting location to the goal, but I can't trace it back, as in actually write down the path. I'm using Vector2f (ordered pair of floats) and Sprite from SFML but all the code there is pretty simple so you won't really need to understand it.
Edit: the problem is with Node.cameFrom. For some reason, it doesn't cout anything but the walls.
Here's Node.h
#ifndef NODE_H
#define NODE_H
#include <SFML/Graphics.hpp>
using namespace sf;
class Node {
public:
Vector2f pos;
// Distance traveled already to reach node
int level;
// Level + estimated dist to goal
int priority;
Node *cameFrom;
Node(Vector2f npos, int lv, Vector2f dest, Node *cf=nullptr);
bool operator == (const Node &nhs) const {
return nhs.priority == priority;
}
};
#endif // NODE_H
Node.cpp
#include "Node.h"
#include <SFML/Graphics.hpp>
#include <math.h>
#include <iostream>
using namespace std;
using namespace sf;
int estimatedDist(Vector2f pos, Vector2f dest) {
return abs(dest.x - pos.x) + abs(dest.y - pos.y);
}
Node::Node(Vector2f npos, int lv, Vector2f dest, Node *cf) {
cameFrom = cf;
level = lv;
pos = npos;
priority = level + estimatedDist(pos, dest);
}
Enemy.cpp pathfind functions
bool occupies(Vector2f pos, vector<Wall> walls) {
for (unsigned w = 0; w < walls.size(); w++) {
if (walls.at(w).collisionBox.getGlobalBounds().contains(pos.x * 32, pos.y * 32)) {
return true;
}
}
return false;
}
bool nFind(Node n, vector<Node> nodes) {
for (unsigned i = 0; i < nodes.size(); i++) {
if (nodes.at(i).pos == n.pos) {
return true;
}
}
return false;
}
void Enemy::pathFind(Vector2f dest, vector<Wall> walls) {
char fullMap[32][22];
vector<Node> openSet;
vector<Node> closedSet;
int xStart, yStart;
for (unsigned y = 0; y < 22; y++) {
for (unsigned x = 0; x < 32; x++) {
if (sprite.getGlobalBounds().top >= y * 32 && sprite.getGlobalBounds().top <= (y + 1) * 32) {
if (sprite.getGlobalBounds().left >= x * 32 && sprite.getGlobalBounds().left <= (x + 1) * 32) {
xStart = x;
yStart = y;
}
} if (occupies(Vector2f(x, y), walls)) {
fullMap[x][y] = '2';
} else {
fullMap[x][y] = ' ';
}
}
}
fullMap[int(dest.x)][int(dest.y)] = 'D';
Node *current = new Node(Vector2f(xStart, yStart), 0, dest);
fullMap[int(current->pos.x)][int(current->pos.y)] = '2';
openSet.push_back(*current);
while (openSet.size() > 0) {
sort(openSet.begin(), openSet.end(), sortByPriority());
*current = openSet.front();
if (current->pos == dest) {
cout << "We gots it ";
for (unsigned y = 0; y < 22; y++) {
for (unsigned x = 0; x < 32; x++) {
if (occupies(Vector2f(x, y), walls)) {
fullMap[x][y] = '2';
} else {
fullMap[x][y] = ' ';
}
}
}
while (current->cameFrom) {
fullMap[int(current->pos.x)][int(current->pos.y)] = 'P';
current = current->cameFrom;
for (unsigned y = 0; y < 22; y++) {
for (unsigned x = 0; x < 32; x++) {
cout << fullMap[x][y];
}
cout << endl;
}
cout << endl;
} for (unsigned y = 0; y < 22; y++) {
for (unsigned x = 0; x < 32; x++) {
cout << fullMap[x][y];
}
cout << endl;
}
cout << endl;
return;
}
openSet.erase(remove(openSet.begin(), openSet.end(), *current), openSet.end());
closedSet.push_back(*current);
fullMap[int(current->pos.x)][int(current->pos.y)] = '2';
vector<Node> neighbors;
neighbors.push_back(Node(Vector2f(current->pos.x - 1, current->pos.y - 1), current->level + 1, dest));
neighbors.push_back(Node(Vector2f(current->pos.x, current->pos.y - 1), current->level + 1, dest));
neighbors.push_back(Node(Vector2f(current->pos.x + 1, current->pos.y - 1), current->level + 1, dest));
neighbors.push_back(Node(Vector2f(current->pos.x + 1, current->pos.y), current->level + 1, dest));
neighbors.push_back(Node(Vector2f(current->pos.x + 1, current->pos.y + 1), current->level + 1, dest));
neighbors.push_back(Node(Vector2f(current->pos.x, current->pos.y + 1), current->level + 1, dest));
neighbors.push_back(Node(Vector2f(current->pos.x - 1, current->pos.y + 1), current->level + 1, dest));
neighbors.push_back(Node(Vector2f(current->pos.x - 1, current->pos.y), current->level + 1, dest));
for (unsigned i = 0; i < neighbors.size(); i++) {
if (nFind(neighbors.at(i), closedSet) ||
neighbors.at(i).pos.x > 22 ||
neighbors.at(i).pos.y > 32 ||
neighbors.at(i).pos.x < 0 ||
neighbors.at(i).pos.y < 0 ||
occupies(neighbors.at(i).pos, walls)) {
continue;
} if (!nFind(neighbors.at(i), openSet)) {
openSet.push_back(neighbors.at(i));
}
neighbors.at(i).cameFrom = current;
}
}
}
MCVE would help to try on our side (see zett42 comment).
So by just a quick look I can give you some pointers where to look during debugging, but no clear answer.
These lines looks highly suspicious:
Node *current = new Node(Vector2f(xStart, yStart), 0, dest);
// ^ no delete in source, will leak memory
*current = openSet.front();
// will overwrite the heap memory with copy constructor
// but the pointer will remain the same
// so all of your nodes will always have "cameFrom"
// pointing to this same memory.
Overall this code looks a bit complicated. Do you have the game with fixed square 32x22 tiles? Why "walls" vector then?
I would maintain only single global tile map as level (but the A* search then shouldn't damage it, rather create it's own copy for search, or rather to have new map with to-reach-costs, that would probably simplify the code a lot).
xStart, yStart can be computed directly, no need to iterate it every loop:
xStart = int(sprite.getGlobalBounds().left)>>5; // left/32
yStart = int(sprite.getGlobalBounds().top)>>5; // top/32
The bool operator == (const Node &nhs) const looks unhealthy, but it's not even used anywhere.
And to see if neighbour is in wall, you don't need to use the O(N) occupies, just test the map for == '2'? (I mean if the code is designed that way, I didn't verify it will work as expected if you change it right away in your code).
Overall I don't like that code, you can streamline that into shorter version, if you focus on what data you want to process and how, and stop moving objects back and forth through several lists. For A* IIRC you should need single sorted queue with insert_at to keep it sorted vs map field to mark which squares were already processed.
Are those Vector2f positions important, for example:
...
P#D
...
If player "P" stands in lower part of square ("#" is wall, "D" is destination), should the A* find the bottom path, or you need only "tile" accuracy and the upper path would be good too?
It's not clear to me from you question, whether you work with sub-tile accuracy or not, if not, then you can drop most of that Vector2f stuff and work only in the tile coordinates.
With sub-tile accuracy you can probably still drop most of it, but if actually tile has "32" size, and player is for example only "3" wide, so he can use the tile as some kind of "area" and move across it by different lines, avoiding in example above to go to full centre of middle tile, saving distance... Then you need to calculate those sub-tile positions somehow in to get at least roughly accurate "shortest" path.
When I was working on one game, we had linked list of nodes (classic math graph) instead of tiles, each node had it's "area radius", and after the shortest node-to-node path was found, another reiterative algorithm did few loops to move from node positions to some shadow-node position which was within the radius, but was closer to the other two shadow-nodes. After hitting max iterations, or the shadow-positions didn't change much (usually it took 3-5 iterations at most), it stopped "smoothing" the path and returned it. This way soldiers were running across desert in almost straight lines, while actually the waypoint nodes were like sparse grid with 20m area radius, so the soldier was actually going only like 2-3 nodes away and starting/ending far away from node centre going almost zig-zag in the node graph itself.
For every tile, you need its cost (cost of getting there plus heuristic), and the identify of the neighbouring tile from which you reached it.
The algorithm has a "balloon" of points round the start point, and the best point is analysed first. So if the path is simple, the balloon is very elongated. If it is convoluted, the balloon is roundish, and many paths get abandoned because hemmed in by walls and already-visited tiles.
The graph:
and how the points are connected:
the file how points are connected are the output i have . The expected output should be 1<->216 , 23<->157 115<->157 and then 115<->216 . The order doesn't matter but those points should be connected this way
Let me ask you a question.
I have the following code:
for (int i = 0; i < values.size()-1;i++)
{
int result = 0;
double Min2 = DBL_MAX;
int x = 0;
for (int j = i+1; j < values.size(); j++)
{
/*if (visited[j] == false)*/
{
distance = sqrt(pow((values[i].x2 - values[j].x2), 2) + pow((values[i].y2 - values[j].y2), 2));
if (distance < Min2 && distance != 0)
{
Min2 = distance;
x = j;
}
}
}
If you look at the graph the left first node is 1 then goes 216 then 115 then 157 and then 23. I have the right connection except for 216-115 but instead of it connects 216-157. Why does it ignore or min distance won't help. I tried to use flag( like if visited or not)the same result. All nodes work , just this one doesn't want to be connected right.
The logic of the code seems a bit odd...
for (int i = 0; i < values.size()-1;i++) {
int result = 0;
double Min2 = DBL_MAX;
int x = 0;
for (int j = i+1; j < values.size(); j++) {
iterating till size()-1 seems like you assume that the relation "closest neighbour" is commutative, but it is not. Consider this example:
a b c
a has b as closest node and (by chance) also b has a as closest node, but c has b as closest node and this connection you would miss.
Further, starting the second loop at i+1 seems rather odd, as it assumes that the points in the vector are already ordered (if this would be the case, then whats the point of searching the closest nodes?).
If you know already, that the nodes are along a route, then I would do it like this:
1) start with the first node n0 in the route (its a bit more complicated if you dont know this node)
2) find the closest node to n0 call it n1
3) continue to find the closest node to ni among the nodes that are not yet connected to the route, call it ni+1
4) repeat 3) until you reach the end of the route.
I have the impression, that you dont understand the difference between those steps and your code. I dont like to give up, so I will try to explain again in a less pseudo way:
int currentNode = startNode; // as mentioned before, if you dont know
// this its a bit more involved
std::vector<int> route;
route.push_back(currentNode);
while (currentNode != endNode) { // also knowing the last node of the route helps...
double minDistance = std::numeric_limits<double>::max();
int nextNode = -1;
for (int i=0;i<nodes.size();i++) {
if (std::find(route.begin(), route.end(), i) == route.end()){
double distance = getDistance(currentNode,i);
if (distance < minDistance) {
minDistance = distance;
nextNode = i;
}
}
}
route.push_back(nextNode);
currentNode = nextNode;
}
Your outer loop shouldnt iterate through all nodes, if you actually want to find only that one route. Also you have to remember nodes that are already in the route (in case each node should appear only once and you dont want a closed loop).
for (int i = 0; i < values.size();i++)
{
int result = 0;
double Min2 = DBL_MAX;
int x = 0;
for (int j =0; j < values.size(); j++)
{
/*if (visited[j] == false)*/
{
distance = sqrt(pow((values[i].x2 - values[j].x2), 2) + pow((values[i].y2 - values[j].y2), 2));
if (distance < Min2 && distance != 0)
{
Min2 = distance;
x = j;
}
}
}
/*visited[i] = true;*/
The problem consists in calculate all possible end positions and how many combinations exist for each one.
Given a start position x=0, a length m of the track and a list of jumps. Return the number of possible ends for each position on the interval [-m/2,+m/2]. The jumps must be done in the same order as given but it could be done in negative or positive way.
For example:
L = 40
jumps = 10, 10
Solution:
-20 : 1 (-10, -10)
0 : 2 (-10,+10 & +10,-10)
20 : 1 (+10,+10)
(The output needed is only the pair "position : #combinations")
I did it with a simple recursion, and the result is OK.
But in large sets of data, the execution time is few minutes or hours.
I know that with dynamic programming I can have a solution in few seconds, but I don't know how can I apply dynamic in this case.
There's my actual recursive function:
void escriuPosibilitats(queue<int> q, map<int,int> &res, int posicio, int m) {
int salt = q.front();
q.pop();
if(esSaltValid(m,posicio,-salt)) {
int novaPosicio = posicio - salt;
if(q.empty()) {
res[novaPosicio]++;
} else {
escriuPosibilitats(q,res,novaPosicio,m);
}
}
if(esSaltValid(m,posicio,salt)) {
int novaPosicio = posicio + salt;
if(q.empty()) {
res[novaPosicio]++;
} else {
escriuPosibilitats(q,res,novaPosicio,m);
}
}
}
Where q is the queue of the remaining jumps.
Where res is the parcial solution.
Where posicio is the actual position.
Where m is the length of the track.
Where esSaltValid is a function that checks if the jump is valid in the range of the track length.
PD: Sorry for my english level. I tried to improve my question! Thanks =)
You can use the following idea. Let dp[x][i] be the number of ways to arrive to the position x using until the jump i. Then the answer would be dp[x][N] for each x, and where N is the number of jumps. Even more, you can realize that this dp depends only on the previous row, and then you can simply dp[x] and save the next row in some auxiliary array, and then replace it in each iteration. The code would be something like this:
const int MOD = (int)(1e8+7);
const int L = 100;
int N = 36;
int dx[] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int dp[L+1];
int next[L+1];
int main() {
int shift = L/2; // to handle negative indexes
dp[shift] = 1; // the initial position has one way to arrive, since you start there
for (int i = 0; i < N; ++i) { // for each jump size
for (int x = -L/2; x <= L/2; ++x) { // for each possible position
if (-L/2 <= x + dx[i] && x + dx[i] <= L/2) // positive jump
next[x + shift] = (next[x + shift] + dp[x + dx[i] + shift]) % MOD;
if (-L/2 <= x - dx[i] && x - dx[i] <= L/2) // negative jump
next[x + shift] = (next[x + shift] + dp[x - dx[i] + shift]) % MOD;
}
for (int x = -L/2; x <= L/2; ++x) { // update current dp to next and clear next
dp[x+shift] = next[x+shift];
next[x+shift] = 0;
}
}
for (int x = -L/2; x <= L/2; ++x) // print the result
if (dp[x+shift] != 0) {
cout << x << ": " << dp[x+shift] << '\n';
}
}
Of course, in case L is too big to handle, you can compress the state space and save the results in a map, and not in an array. The complexity of the approach is O(L*N). Hope it helped.
EDIT: just compute everything modulo 1e8+7 and that's it.
This program should work correctly but it doesn't! assume you are building a minheap by inserting nmubers into an array. Each time of insertion should be followed by Heapify function to make sure that the sort of numbers do not violate the minheap rule. This is what I wrote but there is something wrong with it and I couldn't make it!
int P(int i) //returning the index of parent
{
if (i % 2 == 0) { i = ((i - 2) / 2); }
else { i = ((i - 1) / 2); }
return i;
}
void Heapify(double A[], int i)//putting the smallest value in the root because we have a min heap
{
if (P(i) != NULL && A[i] < A[P(i)])
{
temp = A[P(i)];
A[P(i)] = A[i];
A[i] = temp;
Heapify(A, P(i));
}
}
Generally speaking, your heapify function doesn't seem to take a minimum of both left and right branches into consideration. Let me show you an ideal, working implementation (object-oriented, so you might want to pass the heap as a parameter). You can find the exact pseudocode all over the internet, so I'm not really presenting anything unique.
void Heap::Heapify (int i)
{
int l = left(i);
int r = right(i);
int lowest;
if (l < heap_size && heap[l] -> value < heap[i] -> value )
lowest = l;
else
lowest = i;
if (r < heap_size && heap[r] -> value < heap[lowest] -> value)
lowest = r;
if (lowest != i)
{
swap (heap[i], heap[lowest]);
Heapify(lowest);
}
}
where
int left ( int i ) { return 2 * i; }
int right ( int i ) { return 2 * i + 1; }
As you can see, an algorithm first checks which one of left and right children have lower value. That value is swapped with current value. That is everything there is to it.
I am attempting to make a maze-solver using a Breadth-first search, and mark the shortest path using a character '*'
The maze is actually just a bunch of text. The maze consists of an n x n grid, consisting of "#" symbols that are walls, and periods "." representing the walkable area/paths. An 'S' denotes start, 'F' is finish. Right now, this function does not seem to be finding the solution (it thinks it has the solution even when one is impossible). I am checking the four neighbors, and if they are 'unfound' (-1) they are added to the queue to be processed.
The maze works on several mazes, but not on this one:
...###.#....
##.#...####.
...#.#.#....
#.####.####.
#F..#..#.##.
###.#....#S.
#.#.####.##.
....#.#...#.
.####.#.#.#.
........#...
What could be missing in my logic?
int mazeSolver(char *maze, int rows, int cols)
{
int start = 0;
int finish = 0;
for (int i=0;i<rows*cols;i++) {
if (maze[i] == 'S') { start=i; }
if (maze[i] == 'F') { finish=i; }
}
if (finish==0 || start==0) { return -1; }
char* bfsq;
bfsq = new char[rows*cols]; //initialize queue array
int head = 0;
int tail = 0;
bool solved = false;
char* prd;
prd = new char[rows*cols]; //initialize predecessor array
for (int i=0;i<rows*cols;i++) {
prd[i] = -1;
}
prd[start] = -2; //set the start location
bfsq[tail] = start;
tail++;
int delta[] = {-cols,-1,cols,+1}; // North, West, South, East neighbors
while(tail>head) {
int front = bfsq[head];
head++;
for (int i=0; i<4; i++) {
int neighbor = front+delta[i];
if (neighbor/cols < 0 || neighbor/cols >= rows || neighbor%cols < 0 || neighbor%cols >= cols) {
continue;
}
if (prd[neighbor] == -1 && maze[neighbor]!='#') {
prd[neighbor] = front;
bfsq[tail] = neighbor;
tail++;
if (maze[neighbor] == 'F') { solved = true; }
}
}
}
if (solved == true) {
int previous = finish;
while (previous != start) {
maze[previous] = '*';
previous = prd[previous];
}
maze[finish] = 'F';
return 1;
}
else { return 0; }
delete [] prd;
delete [] bfsq;
}
Iterating through neighbours can be significantly simplified(I know this is somewhat similar to what kobra suggests but it can be improved further). I use a moves array defining the x and y delta of the given move like so:
int moves[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
Please note that not only tis lists all the possible moves from a given cell but it also lists them in clockwise direction which is useful for some problems.
Now to traverse the array I use a std::queue<pair<int,int> > This way the current position is defined by the pair of coordinates corresponding to it. Here is how I cycle through the neighbours of a gien cell c:
pair<int,int> c;
for (int l = 0;l < 4/*size of moves*/;++l){
int ti = c.first + moves[l][0];
int tj = c.second + moves[l][1];
if (ti < 0 || ti >= n || tj < 0 || tj >= m) {
// This move goes out of the field
continue;
}
// Do something.
}
I know this code is not really related to your code, but as I am teaching this kind of problems trust me a lot of students were really thankful when I showed them this approach.
Now back to your question - you need to start from the end position and use prd array to find its parent, then find its parent's parent and so on until you reach a cell with negative parent. What you do instead considers all the visited cells and some of them are not on the shortest path from S to F.
You can break once you set solved = true this will optimize the algorithm a bit.
I personally think you always find a solution because you have no checks for falling off the field. (the if (ti < 0 || ti >= n || tj < 0 || tj >= m) bit in my code).
Hope this helps you and gives you some tips how to improve your coding.
A few comments:
You can use queue container in c++, its much more easier in use
In this task you can write something like that:
int delta[] = {-1, cols, 1 -cols};
And then you simple can iterate through all four sides, you shouldn't copy-paste the same code.
You will have problems with boundaries of your array. Because you are not checking it.
When you have founded finish you should break from cycle
And in last cycle you have an error. It will print * in all cells in which you have been (not only in the optimal way). It should look:
while (finish != start)
{
maze[finish] = '*';
finish = prd[finish];
}
maze[start] = '*';
And of course this cycle should in the last if, because you don't know at that moment have you reach end or not
PS And its better to clear memory which you have allocate in function