The code goes like this. It's a BFS, and I want it to go backwards, so I try to have a connection between steps using a pointer.
sx, sy are our starting points. tx, ty are our destiny points. act[][] is a Boolean table to ensure that I won't go into the same place twice.
struct trip
{
int first;
int second;
trip* last;
};
void write(trip a)
{
cout<<"\n";
cout<< "x" << " " << a.first << "\n";
cout<< "y" << " " << a.second << "\n";
cout<< "x lasta" << " " << a.last->first << "\n";
cout<< "y lasta" << " " << a.last->second << "\n";
}
queue<trip> Q;
trip P; P.first = sx; P.second = sy; P.last = nullptr; Q.push(P);
while(!Q.empty())
{
//cout << "WOW" << "\n";
trip temp = Q.front(); Q.pop();
if(temp.last != nullptr)
write(temp);
int corx = temp.first; int cory = temp.second;
if(corx == tx && cory == ty)
{
// We found our destiny
}
if(act[corx][cory] == false)
{
act[corx][cory] = true;
// Up
if(cory - 1 >= 0)
{
trip TEMPUUS; TEMPUUS.first = corx - 1; TEMPUUS.second = cory; TEMPUUS.last = &temp; Q.push(TEMPUUS);
cout << corx - 1 << " " << TEMPUUS.last -> first; // corx - 1 here is equal to
//TEMPUUS.last -> first - 1 and that is what I want
}
// Down
if(cory + 1 <= 2000)
{
trip TEMPUUS; TEMPUUS.first = corx + 1; TEMPUUS.second = cory; TEMPUUS.last = &temp; Q.push(TEMPUUS);
}
// Left
if(corx - 1 >= 0)
{
trip TEMPUUS; TEMPUUS.first = corx; TEMPUUS.second = cory - 1; TEMPUUS.last = &temp; Q.push(TEMPUUS);
}
// Right
if(corx + 1 <= 2000)
{
trip TEMPUUS; TEMPUUS.first = corx; TEMPUUS.second = cory + 1; TEMPUUS.last = &temp; Q.push(TEMPUUS);
}
}
}
So what's the problem? The problem is that when I push a trip variable to the queue its coordinates are different from its predecessor's. However, as we go into the next iteration of the queue, the temp
variable goes out of scope and the "last" pointer now points at itself.
There is a code sample:
#include <iostream>
#include <fstream>
#include <queue>
using namespace std;
struct trip
{
int first;
int second;
trip* last;
};
void write(trip a)
{
cout << "\n";
cout << "x" << " " << a.first << "\n";
cout << "y" << " " << a.second << "\n";
cout << "x lasta" << " " << a.last->first << "\n";
cout << "y lasta" << " " << a.last->second << "\n";
}
void bfs(int sx, int sy, int tx, int ty)
{
queue<trip> Q;
trip P; P.first = sx; P.second = sy; P.last = nullptr; Q.push(P);
int test = 0;
while(!Q.empty())
{
trip temp = Q.front(); Q.pop();
if(temp.last != nullptr)
write(temp);
int corx = temp.first;
int cory = temp.second;
if(act[corx][cory] == false)
{
act[corx][cory] = true;
// Up
if(cory - 1 >= 0)
{
trip TEMPUUS; TEMPUUS.first = corx - 1; TEMPUUS.second = cory; TEMPUUS.last = &temp; Q.push(TEMPUUS);
cout << corx - 1 << " " << TEMPUUS.last -> first;
}
}
test++;
if(test > 5)
return;
}
}
int main()
{
int sx, sy, tx, ty;
cin >> sx >> sy >> tx >> ty;
sx += 1000; sy += 1000; tx += 1000; ty += 1000;
bfs(sx, sy, tx, ty);
return 0;
}