ed-learner / basics-of-c-plus-plus

An introduction to basics of c++
GNU General Public License v3.0
0 stars 0 forks source link

Implement a depth or breadth first graph traversal #2

Open teodron opened 4 years ago

teodron commented 4 years ago

Create a C++ class to manage a directed graph

Use a node struct e.g. like struct Node { double data[2]; std::vector<Node*> reachableNeighbors; }; Make the class manage a std::vector given that you know how many nodes the graph has. class Graph { public: // returns the index of the node in the std::vector structure size_t addNode(double x, double y); void addEdge(size_t fromIndex, size_t toIndex);

void breadthFirst(size_t nodeIndex) const; void depthFirst(size_t nodeIndex) const;

private: std::vector<Node*> nodes; };

Read the graph structure from a file. Eg 3 - no of nodes 0 0 - coords of first point 1 0 - 2nd 1 1 -3rd 3 - no of graph edges 0 1 - from 0 -> 1 1 2 - 1->2 0 2 - 0 ->2

which should describe a graph just like this one 2 ^ ^ / \ 0---->1

The dfs from 0 should print: 1 1 1 0 0 0 Whereas the bfs from 0 should print 0 0 1 0 1 1

teodron commented 4 years ago

https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/ https://www.softwaretestinghelp.com/cpp-bfs-program-to-traverse-graph/