When traversing an undirected graph using breadth first search that has no parallel edges and self loops, there exists a vertex x with an adjacent vertex y. When processing vertex "x" it sees that y is already discovered/visited and has a parent/discoverer that is not x and
- case 1) y is processed
- case 2) y is not processed
What is are sample situations for each of them to happen? and does it say anything about relationship between x and y?
where, Processed vertex means we have already traversed all of its adjacent vertices Discovered node means y has been discovered by atleast one of its parents. Parent means the vertex that first discovered a given vertex.
Heres my thinking. Clearly, y has atleast 2 parent vertices. "x" and atleast one more parent "a".
a x
\ /
y
and since y is already discovered in both cases (1) and (2)
(case 1) is possible because "a" and "x " (parents of y) dont have any common ancestors or x must have been processed before y. Correct??? or not?
(case 2) "a" and "x" must have a common ancestor therefore x is being processed before y. Correct???? or not?
Just for reference, heres the implementation of bfs (see the traverse() function) including a main() based on Steven Skiena's "Algorithm Design Manual" book
#include <iostream>
#include <queue>
class edgeNode {
private:
int y{ -1 };
edgeNode* next{ nullptr };
public:
edgeNode(int _y, edgeNode* _node) : y{ _y }, next{ _node }{}
edgeNode(int _y) : y{ _y }, next(nullptr){}
edgeNode() : y(0), next(nullptr) {}
int getY() const { return y; }
edgeNode* getNext() const { return next; }
void print() { std::cout << y; }
};
class bGraph {
static const int MAX_VERTICES = 100;
edgeNode* edges[MAX_VERTICES];
bool discovered[MAX_VERTICES];
bool processed[MAX_VERTICES];
int parents[MAX_VERTICES];
public:
bGraph() {
for (int i = 0; i < MAX_VERTICES; i++) {
edges[i] = nullptr;
discovered[i] = false;
processed[i] = false;
parents[i] = -1;
}
}
edgeNode* getEdge(int v) { return edges[v]; }
void addEdge(int x, int y, bool directed) {
edgeNode* node = new edgeNode(y, edges[x]);
edges[x] = node;
if (!directed) {
addEdge(y, x, true);
}
}
void traverse(int v) {
int x, y;
std::queue<int> fifo;
fifo.push(v);
while (!fifo.empty()) {
x = fifo.front();
fifo.pop();
edgeNode* node = getEdge(x);
if (node == nullptr)
continue;
discovered[x] = true;
std::cout << "\nStart Processing Vertex: " << x << std::endl;
while (node != nullptr) {
y = node->getY();
if (!processed[y] ) {
//process edge
std::cout << "(" << x << "," << y << ") ";
}
if (!discovered[y]) {
fifo.push(y);
parents[y] = x;
discovered[y] = true;
}
node = node->getNext();
}
processed[x] = true;
std::cout << "\nDone Processing Vertex: " << x << std::endl;
}
}
};
int main()
{
bGraph g;
g.addEdge(1,2, false);
g.addEdge(3,1, false);
g.traverse(1);
return 0;
}