-I wrote a program to find the shortest path from a source node to a target node. Everything is fine, the program found the shortest path. But i have a problem, that is not able to print or get each node in the path. I tried many ways but no result. Hope anyone can help me, thanks everyone.
///////////////////////////////
#include <vector>
#include <queue>
#include <iostream>
#include <algorithm>
typedef struct Node
{
int vertex;
int g;
int h;
int f;
Node* parent;
Node(int vertex)
{
this->vertex = vertex;
this->g = 0;
this->h = 0;
this->f = 0;
this->parent=NULL;
}
Node(int vertex,int g, int h, int f,Node*parent)
{
this->vertex = vertex;
this->g = g;
this->h = h;
this->f = f;
this->parent = parent;
}
}Node;
struct Edge
{
int source;
int dest;
int g;
int h;
};
struct comp
{
bool operator()(const Node* lhs, const Node* rhs) const {
return lhs->f < rhs->f;
}
};
std::vector<Node*>openList;
std::vector<Node*>closeList;
Node* startPos;
Node* endPos;
static const int WeightW = 10;
class Graph
{
public:
std::vector<std::vector<Edge>>adjlist;
Graph(const std::vector<Edge>& edges, int N)
{
adjlist.resize(N);
for (auto &edge:edges)
{
adjlist[edge.source].push_back(edge);
}
}
};
int isContains(std::vector<Node*>* Nodelist, int vertex);
void printPath(Node*node);
void findShortestPath(const Graph& grap,Node* start,Node* end, int N)
{
Node* node;
openList.push_back(start);
while (openList.size()>0)
{
node = openList[0];
closeList.push_back(node);
openList.erase(openList.begin());
std::cout << "start" << std::endl;
int u = node->vertex;
std::cout << "V: " << u << " g :" << node->g << std::endl;
std::cout << "continous" << std::endl;
for (auto v : grap.adjlist[u])
{
if (v.dest == end->vertex)
{
std::cout << "FindNode " << v.dest << std::endl;
printPath(node);
return;
}
if (isContains(&closeList, v.dest) == -1)
{
if (isContains(&openList, v.dest) == -1)
{
int vertex = v.dest;
std::cout <<"V: "<< vertex << std::endl;
int h = v.h;
int currentg = node->g + v.g;
int f = currentg + h;
std::cout <<"vertext: "<<vertex<< " h: " << h << " g: " << currentg << " f: " << f << std::endl;
Node* newNode = new Node(vertex, currentg, h, f,node->parent);
openList.push_back(newNode);
}
}
}
std::cout<<"Close: ";
for (size_t i = 0; i < closeList.size(); i++)
{
std::cout << closeList[i]->vertex << " ";
}
std::cout << std::endl;
sort(openList.begin(), openList.end(),comp());
std::cout << "Open: ";
for (size_t i = 0; i < openList.size(); i++)
{
std::cout << openList[i]->vertex << " ";
}
std::cout << std::endl;
std::cout << "end" << std::endl;
std::cout << std::endl;
}
}
void printPath(Node* node)
{
std::cout << std::endl;
if (node->parent != NULL)
printPath(node->parent);
std::cout << node->vertex << " ";
}
int isContains(std::vector<Node*>* Nodelist,int vertex)
{
for (int i = 0; i < Nodelist->size(); i++)
{
if (Nodelist->at(i)->vertex== vertex)
{
return i;
}
}
return -1;
}
int main()
{
//{Node,Node,G,H}
//Firt Node
//second Node
//G is the movement cost to move from the starting point to a given square on the grid
// following the path generated to get there
//H is the estimated movement cost to move from that given square on the grid to the final destination
std::vector<Edge>edges =
{
{0,1,5,17},
{0,2,5,13},
{1,0,5,16},
{1,3,3,16},
{1,2,4,13},
{2,0,5,16},
{2,1,4,17},
{2,3,7,16},
{2,4,7,16},
{2,7,8,11},
{3,2,7,13},
{3,7,11,11},
{3,10,16,4},
{3,11,13,7},
{3,12,14,10},
{4,2,7,13},
{4,5,4,20},
{4,7,5,11},
{5,4,4,16},
{5,6,9,17},
{6,5,9,20},
{6,13,12,7},
{7,3,11,16},
{7,4,5,16},
{7,8,3,10},
{8,7,3,11},
{8,9,4,8},
{9,8,4,10},
{9,13,3,7},
{9,15,8,0},
{10,3,16,16},
{10,11,5,7},
{10,13,7,7},
{10,15,4,0},
{11,3,13,16},
{11,10,5,4},
{11,12,9,10},
{11,14,4,5},
{12,3,14,16},
{12,11,9,7},
{12,14,5,5},
{13,9,3,8},
{13,10,7,4},
{13,15,7,0},
{14,11,4,7},
{14,12,5,10},
{15,9,8,8},
{15,10,4,4},
{15,13,7,7},
};
int n = edges.size();
Graph grap(edges, n);
//std::cout << h << std::endl;
Node* start = new Node(0);
Node* end = new Node(15);
findShortestPath(grap, start, end, n);
//Astar astar;
//Node* startPos = new Node(5, 1);
//Node* endPos = new Node(1, 8);
//astar.printMap();
//astar.search(startPos, endPos);
//cout << endl;
//astar.printMap();
system("pause");
return 0;
}
Your program doesn't find the shortest path. It gives the wrong output. (you're on the right track though)
I will assume you are trying to find the shortest path by using BFS. Let's take a look at line 113:
sort(openList.begin(), openList.end(),comp());
Here you're sorting your BFS queue (vector in your case) and thus destroying the right order.
Delete that line.
Congrats, now your program finds the shortest path!
Next, as I understand, for each node you branch into, you remember which node you came from in order to backtrack the path once you reach the destination or final node.
In line 102:
Node* newNode = new Node(vertex, currentg, h, f,node->parent);
you are assigning the new node's grandparent instead of parent. Change that line to
Node* newNode = new Node(vertex, currentg, h, f,node);
Now your printPath function works properly and prints the right path. (just add the target node)
Anyways, your code has a lot of space for improvements. Check out other implementations online and try to see if you can code it as short and clean for practice. Good luck!
I have a doubly-linked list and I want to sort the users by their ELO.
The problem is that when the function swap() is called, some users dissapear
This is what I get in my console:
https://imgur.com/a/pJSPSnW
As you can see, the first swap (between players 1 and 2) is done correctly.
But, when it swaps players 3 and 4, user1 dissapears.
I think that the problem is inside the function swap(), but I can't figure out where exactly
Code:
User/Node declaration
struct user {
public:
string username;
float ELO = NULL; //Score of the user
user* next = nullptr;
user* previous = nullptr;
};
QuickSortRecursive function
void ELOManager::_quickSortRecursive(user* low, user* high) {
if (high != nullptr && low != high && low != nullptr) {
user* p = partition(low, high);
_quickSortRecursive(low, p->previous);
_quickSortRecursive(p->next, high);
}
}
QuickSort function
void ELOManager::quickSort(){
_quickSortRecursive(first, last);
}
Partition function
user* ELOManager::partition(user* low, user* high) {
float pivot = high->ELO;
user* i = low->previous;
for (user* j = low; j != high && j!=nullptr; j = j->next) {
if (j->ELO <= pivot){
i = (i == NULL) ? low : i->next;
swap(i, j);
}
}
//i = (i == NULL) ? low : i->next;
swap(i->next, high);
cout << endl << "Loop finished -----------------------" << endl;
printUsers();
return i;
}
Swap function
void ELOManager::swap(user* A, user* B) {
user* tmp = new user();
user* swapperVector[4];
cout << endl << "swap1[" << A->username << "]" << endl;
cout << "swap2[" << B->username << "]" << endl;
if (A == B) {
cout << "Same Users: Continue" << endl;
return;
}
swapperVector[0] = A->previous;
swapperVector[1] = B->previous;
swapperVector[2] = A->next;
swapperVector[3] = B->next;
if (areTheyNeighbours(A, B)) {
A->previous->next = B;
A->next->previous = B;
B->previous->next = A;
B->next->previous = A;
A->previous = B;
B->previous = swapperVector[1];
A->next = swapperVector[3];
B->next = A;
cout << endl << "Option 1" << endl;
}
else {
A->previous = swapperVector[1];
B->previous = swapperVector[0];
A->next = swapperVector[3];
B->next = swapperVector[2];
A->previous->next = B;
A->next->previous = B;
B->previous->next = A;
B->next->previous = A;
cout << endl << "Option 2" << endl;
}
cout <<"Print list after swap" << endl << "-----" << endl;
printUsers();
}
Feel free to get into my project's github
https://github.com/pablogalve/ELO-System
I would appreciate your help :)
In your if (areTheyNeighbors(A, B)) block, your linked list pointers end up looking like this:
Notice that:
Both of B's pointers are pointed at A
Both A and A->next think B is their previous list element
This causes multiple problems in list traversal, and might be what causes the first element in the list to be lost.
If A and B are neighbors, this should swap them properly.
A->previous = B;
B->previous = swapperVector[0];
A->next = swapperVector[3];
B->next = A;
Amanda's answer shows one way to deal with adjacent nodes, but there doesn't need to be a special case to handle adjacent versus non-adjacent nodes, if the swapping is done first by swapping what is pointing to the two target nodes, then swapping the pointers within the two target nodes.
AP = A->previous;
BP = B->previous;
AN = A->next;
BN = B->next;
std::swap(AN->previous, BN->previous);
std::swap(AP->next, BP->next);
std::swap(A->previous, B->previous);
std::swap(A->next, B->next);
I have a problem with finding cycles in graph. In the condition we have to find the shortest cycle in directed graph.
My graph is (A,B,C,D) and the connections (arcs) between the elements are:
(A->B), (A->A), (B->C), (B->A), (C->D), (C->A), (D->A)
and so cycles are the following:
А->B->C->D->A; A->B->C->A; A->B->A; A->A.
Program should print the shortest cycle, ie A->A. To solve it i need first to find all cycles, then put them each in a separate list and finally bring the smallest list, which will be the shortest cycle (A-> A), but I do not know how to realize it. At the moment I made connections (arcs) between elements.
This is my code:
#include <iostream>
using namespace std;
const int N = 10;
struct elem
{
char key;
elem *next;
} *g1[N];
void init(elem *g[N])
{
for (int i = 0; i < N; i++)
g[i] = NULL;
}
int search_node(char c, elem *g[N])
{
for (int i = 0; i < N; i++)
if (g[i])
if (g[i]->key == c)
{
return 1;
}
return 0;
}
int search_arc(char from, char to, elem *g[N])
{
if (search_node(from, g) && search_node(to, g))
{
int i = 0;
while (g[i]->key != from) i++;
elem *p = g[i]->next;
while (true)
{
if (p == NULL)
{
break;
}
if (p->key == to)
{
return 1;
}
p = p->next;
}
}
return 0;
}
void add_node(char c, elem *g[N])
{
if (search_node(c, g))
cout << "Node already exists.\n";
int i = 0;
while (g[i] && (i < N)) i++;
if (g[i] == NULL)
{
g[i] = new elem;
g[i]->key = c;
g[i]->next = NULL;
}
else
{
cout << "Maximum nodes reached.\n";
}
}
void add_arc(char from, char to, elem *g[N])
{
if (search_arc(from, to, g))
cout << "Arc already exists.\n";
else
{
if (!search_node(from, g))
add_node(from, g);
if (!search_node(to, g))
add_node(to, g);
int i = 0;
while (g[i]->key != from) i++;
elem *p = new elem;
p->key = to;
p->next = g[i]->next;
g[i]->next = p;
}
}
void print(elem *g[N])
{
for (int i = 0; i < N; i++)
{
if (g[i] != NULL)
{
elem *p = g[i];
while (p)
{
cout << p->key << "\t";
p = p->next;
}
cout << endl;
}
}
}
void iscycle(elem *g[N])
{
}
int main()
{
system ("cls");
cout << "init: " << endl;
init(g1);
cout << "graph 1: " << endl;
add_arc('a', 'b', g1);
add_arc('a', 'a', g1);
add_arc('b', 'c', g1);
add_arc('b', 'a', g1);
add_arc('c', 'a', g1);
add_arc('c', 'd', g1);
add_arc('d', 'a', g1);
print(g1);
cout << "cycles: ";
iscycle(g1);
system("pause");
return 0;
}
This is my example graph picture: graph
If You're looking for a complete answer, then just check other answers - there are tons of questions regarding used algorithms and I've also found an answer with code ported to many different programming languages (Cpp version is also there)
Algorithm explanation
C++ version
I'd strongly recommend though, that You take a look at algorithms and implement them here, without removing already written code. It's much better to write it yourself, then just copy-past - You'll learn a lot more ;)
If You need any more precise help, write Your current status & we'll see.
i have a c2280 error in c++ and i don't know how to solve it.
here is the code:
#include <iostream>
#include <queue>
#include <deque>
#include "State.h"
#include <assert.h>
#define MAXIMUM_NUMBER_OF_STATES 1000
#define DELTA_Q 0.1
using namespace std;
class RRT
{
private:
float inc_dist;
State start;
State goal;
deque<State> states = deque<State>();
bool goal_is_reached = false;
float RRT::random(float min, float max){
// check if min is less than max , if not then exception is thrown
assert(max >= min);
float range = max - min;
float random;
random = rand() / RAND_MAX;
return (random * (range)) + min;
}
State RRT::randomState(State current_state){
State state = State();
srand(time(0));
while (inStates(state))
{
state.x = random(min(current_state.x, goal.x), max(current_state.x, goal.x));
state.y = random(min(current_state.y, goal.y), max(current_state.y, goal.y));
state.z = random(min(current_state.z, goal.z), max(current_state.z, goal.z));
}
return state;
}
bool RRT::inStates(State state){
for (int i = 0; i < states.size(); i++){
if (states.at(i).x == state.x && states.at(i).y == state.y && states.at(i).z==state.z)
return true;
}
return false;
}
bool RRT::goalTest(State state){
if (state.x == goal.x && state.y == goal.y && state.z == goal.z){
return true;
}
else
return false;
}
void RRT::Successor(State state){
State temp3;
State temp2;
cout <<endl<< "was"<<endl;
if (goalTest(state) || states.size() == MAXIMUM_NUMBER_OF_STATES){
return;
}
getNearistNeighbor(temp3=randomState(state));
cout << "random x: " << temp3.x << " random y: " << temp3.y << " random z: " << temp3.z << endl;
temp2 = State(temp3);
temp2.setFather(state);
states.push_back(temp2);
states.back().setFather(state);
Successor(states.back());
return;
}
State RRT::getNearistNeighbor(State sub_goal_state){
float min_dist = 0, temp;
State desired_state;
for (int i = 0; i < states.size(); i++){
temp = distanceBetweenTwoStates(states.at(i), sub_goal_state);
if (temp < min_dist){
min_dist = temp;
desired_state = State(states.at(i));
}
}
return desired_state;
}
void RRT::generatePath(State state){
cout << endl << "1" << endl;
if (!state.checkIfNull()){
cout << endl << "end" << endl;
return;
cout << endl << "2" << endl;
generatePath(*state.getFather().get());
path.push_back(state);
}
cout << endl << "2" << endl;
generatePath(*state.getFather().get());
path.push_back(state);
return;
}
float RRT::distanceBetweenTwoStates(State state1, State state2){
float x_distance, y_distance, z_distance;
x_distance = sqrt(pow((state1.x - state2.x), 2));
y_distance = sqrt(pow((state1.y - state2.y), 2));
z_distance = sqrt(pow((state1.z - state2.z), 2));
return x_distance + y_distance + z_distance;
}
public:
deque<State> path = deque<State>();
deque<float*> xyzs = deque<float*>();
RRT::RRT(){
}
RRT::RRT(float* starting_point, float* goal_point)
{
start = State(starting_point);
goal= State(goal_point);
states.push_back(start);
}
deque<float*> RRT::getPath(){
Successor(start);
for (int i = 0; i < states.size();i++)
{
if (goalTest(states.at(i))){
goal_is_reached = true;
path.push_back(states.at(i));
break;
}
}
if (goal_is_reached==false){
path.push_back(getNearistNeighbor(goal));
}
State state;
state=State(path.at(0));
path.pop_front();
cout << endl << "x: " << state.x;
cout << endl << "y: " << state.y;
cout << endl << "z: " << state.z << endl;
generatePath(state);
convertToXYZ();
return xyzs;
}
void convertToXYZ(){
State temp;
float* xyz = new float[3];
for (int i = 0; i < path.size(); i++){
temp = path.at(i);
xyz[0] = temp.x;
xyz[1] = temp.y;
xyz[3] = temp.z;
xyzs.push_back(xyz);
}
}
};
here is the code for State.h:
#include <memory>
using namespace std;
class State
{
private:
unique_ptr<State> father;
public:
float x;
float y;
float z;
State(float *xyz){
x = 0;
y = 0;
z = 0;
father = NULL;
}
State(){
x = 0;
y = 0;
z = 0;
father = NULL;
}
State(State& state) : father(new State(*state.father)), x(state.x), y(state.y), z(state.z) {}
State(unique_ptr<State>& state) : father(new State(*state.get())){}
void setFather(State& state){
father.reset(new State(state));
}
unique_ptr<State> getFather(){
unique_ptr<State> temp(new State(*this));
return temp;
}
bool checkIfNull(){
if (father){
return true;
}
else
return false;
}
};
i have been trying to solve this problem but i have not succeed so i need your help guys please help me in solving this.
thanks in advance.
here is the error:
Error 8 error C2280: 'std::unique_ptr<State,std::default_delete<_Ty>> &std::unique_ptr<_Ty,std::default_delete<_Ty>>::operator =(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function c:\users\userr\documents\visual studio 2013\projects\devo controller\devo controller\rrt.h 186 1 Devo Controller
again thanks in advance.
unique_ptr<State> getFather(){
unique_ptr<State> temp(new State(*this));
return temp;
}
you can't return unique_ptr . returning a value from function means using the copy constructor. the copy constructor is disabled for unique_ptr. why? because you can't copy a unique_ptr , it's unique! you need to use shared_ptr if many pointers are to point to a specific object. the same goes for the assignment operator ( = ) .
PS. I think it's deprecated to explicitly assign object memory addres to unique_ptr (with new) , the new standard forces you to use std::make_unique in order to assign something to unique_ptr.
also, try googling your error first, you'll be surprised how many answers there are out there