I'm not really having a coding issue or compiling problem . I am having more or less a design choice. Rather I want to see if there are more (or better) ways to do it than I thought of.
I have a data structure of a directed graph, represented by a kind of adjacency list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
template < typename T >
class Location
{
public:
T m_name;
LinkedList<Location<T>* > m_neighbors;
Location(T l):m_name(l) {}
Location(){}
~Location();
};
template < typename T >
class Graph
{
public:
string m_name;
LinkedList<Location<T> > m_graph;
Graph(const string& s = ""):m_name(s) {}
~Graph();
};
|
Here is the pseudo-code I found on wikipedia for Breadth-First search.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
1 procedure BFS(G,v):
2 create a queue Q
3 enqueue v onto Q
4 mark v
5 while Q is not empty:
6 t ← Q.dequeue()
7 if t is what we are looking for:
8 return t
9 for all edges e in G.adjacentEdges(t) do
10 u ← G.adjacentVertex(t,e)
11 if u is not marked:
12 mark u
13 enqueue u onto Q
14 return none
|
Each location has a re-sizable list of location pointers. So I guess locations are the node class. The Graph object is just helps to encapsulate and provide functionality.
My problem is that with breadth first or even the depth first search algorithm require that a location/node/whatever be marked if it hasn't been marked. I understand by marking each location, the code won't potentially infinity loop.
My first thought was put a bool in every location object. But then after the Breadth first search was over, I would have to make a function that sets each bool in each location to false.
Another thought was to put a check before pushing locations or locations pointers on the queue. Search the queue to see if the location is there or not. if it is not, then simply push that location on the list. But this could hurt speed performance, if there is a lot of data so it makes me feel a little uneasy.
The whole reason I tried the whole adjacency list with pointers is because I wanted a re-sizable, memory efficient data structure. Adjacency matrices are easy, and very speed efficient but there value in speed quickly down when trying to map data that is not inherently numeric in nature.
If you have a graph of ints represented by a 2d-array, and you know node 5 has an edge that goes to node 100 then it is all you have to do to access that neighbor of 5 is array[100]. Instant almost. But if you have a graph of lets say strings represented by a 2d array adjacency matrix, And you figure out that node "St. Louis" is connected to "Chicago", how do you get to Chicago's neighbors? Iterate through the entire list until you find Chicago. That is the only way I figure you can do it with an adjacency matrix anyway.
So if there are any other ways I could go about it, I would like to hear them. Or if the ways I suggest are basically the only practical ways to do it, I guess that is fine too.