Iam new to c++.I have to write a c++ program representing a graph where the node has many edges as input and single edge as its output.I should also label them.I felt using linked list would help me but i was struck by the thought that in a linked list i would only have a single edge to a given node and another edge going to the next node.Is there any possible way of representing many different edges from different nodes to a single node.
So a node should look something like this:
struct Node
{
Node(std::string label_) : label(label_) {}
std::string label;
std::vector<Node*> incoming;
Node* outgoing = nullptr;
}
Then it's just a matter of wiring them together. Note this is sort of like a linked list of strings, except that the "previous" pointer (incoming) is multiple instead of singular.
From here, note that what you are actually building is a tree (assuming one node has a null outgoing pointer). That may help you to find an existing data structure implementation that you can use instead of building your own.
Related
I saw the following implementation of topological sort using DFS on Leetcode https://leetcode.com/problems/course-schedule/discuss/58509/18-22-lines-C++-BFSDFS-Solutions
Now the part of this that is confusing me is the representation of the directed graph which is used for the top sort. The graph is created as follows:
vector<unordered_set<int>> make_graph(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<unordered_set<int>> graph(numCourses);
for (auto pre : prerequisites)
graph[pre.second].insert(pre.first);
return graph;
}
What is confusing me is this line:
graph[pre.second].insert(pre.first);
Presumably the graph is being represented as an adjacency list; if so why is each node being represented by the incoming edges and not the outgoing edges? Interestingly, if I flip pre.second and pre.first like this:
graph[pre.first].insert(pre.second);
The top sort still works. However, it seems most implementations of the same problem use the former method. Does this generalize to all directed graphs? I was taught in my undergraduate degree that a directed graph's adjacency list should contain a list of each nodes outgoing nodes. Is the choice of incoming vs outgoing node arbitrary for the representation of the adjacency list?
To the specific problem which only requires answering true or false, it doesn't matter if you flip every edge. That's because a graph is topological sortable if and only if it has no loops. But if you want an order of taking, it doesn't work as you can see in the different results of [[0, 1]] and [[1, 0]].
Which way to save the graph depends on how you solve the problem. In this given case, we need to know the indegrees of every node (course) and also to update it every time we delete a node from the graph (take the course), so that we know if we can delete a node (we can do it when the indegree is 0). When updating, we minus 1 to each node that the deleted node direct to. If you apply this method (as most do), it's clear how you should save the graph
I am trying to find all the possible paths from one node in my graph that will visit all other nodes in the graph. I want the function to produce all possibilities of paths in my n*m graph. Each node in my graph has a vector of all neighbors nodes and a Boolean that check if the node is visited or not.
example:
a b
c d
will produce:
abcd
abdc
acbd
...
I tried the solution in this answer, but only return one path. How can I produce all possible paths?
It seems like in some situations by your description you could have infinite paths and a path of infinite length because you didn't specify that nodes couldn't be revisited.
You should implement depth first search and pass a reference to an array of marked (visited) nodes in your recursive DFS method assuming that you have a count of the number of nodes in your graph. After you visit each node, before you leave that node make sure you set it to false again so that it can be reaccessed via another node.
The implementation of this algorithm is really going to depend on how you implemented your graph structure and without the details all I can do is speculate that you have a linked structure with an adjacency list representing the different nodes. I also have no idea how the different nodes map to characters so that is another detail I have to speculate, but say that the nodes are represented by integers.
You need to pass into a DFS method the following: array of marked nodes, a linked list which contains the path information, starting node, (i.e, current node) and final node
void printAllPaths(LinkedList<Integer> currentPath, boolean[] marked, int current, int last){
for( all nodes adjacent to current, node ){
if(node == last){
currentPath.addLast(last);
System.out.println(currentPath);
currentPath.removeLast();
}else if(!marked[node]){
currentPath.addLast(node);
marked[node] = true;
printAllPaths(currentPath, marked, node, final);
marked[node] = false;
currentPath.removeLast();
}
}
}
This will be the basic idea of the code. I apologize if it doesn't compile in advance, but this should print out all of the paths.
So, I've implemented a directed graph using an unordered multimap. Each pair within the map is made up of two strings: the vertex and its adjacent vertex.
Now, I am trying to determine if my graph has a cycle, and if so, how big is the cycle. This is the code I have so far:
int findCycle(const unordered_multimap<string,string> & connectedURLVertices, string y, string key)
{
string position;
position=y.find(key);
if(position!=string::npos)
{
return 1;
}
auto nodesToCheck=connectedURLVertices.equal_range(key);
for(auto & node : nodesToCheck)
{
int z=findCycle(connectedURLVertices,y+key,node);
}
}
I've walked through the code on paper and it seems to be logically correct, but I would appreciate it if anyone could take a look and see if I am on the right track or missing anything. Thanks!
To search for cycles in a graph you have to descend recursively through the arcs from some initial node until you reach one already visited node (you can construct a std::set of already visited nodes or mark the nodes as you visit them) or exhaust all the nodes without getting one already visited (absence of cycles) The criterion to select the arc can be adjusted to find it more quickly or the kind of search (first in depth, search by level, etc.)
I want to create a graph with nodes and edges, where each node will contain n number of values. We would be given with the n values of the starting node, from which we need to generate other nodes where each value in each node would be of the form either:
t_n=t_(n-1)+2
or
t_n=t_(n-1)-1
When such a node is generated, it should create an edge from the old node to the new node.
I know this might be very trivial job, but I have very limited programming knowledge. I have been suggested to use classes in C++ or structure to represent the nodes. Please help me in creating the graph with nodes that would have multiple values and further the next nodes would be generated from the parent node following the above rule. Some C++ code would be very helpful.
Thanks in Advance.
here you have some code but I don't really fully understand your task.
- graph with nodes and edges
- each node has n number of values
- we are given n values of the starting point
- need to generate other nodes where each value in each node would be either
- t_n=t_(n-1)+2
- t_n=t_(n-1)-1
- when such node is generated, it creates an edge from the old node to the new node.
this starting point: do we have to generate a graph from it? what is with the creation of the edge from the old node and the new node? is old node here the starting point?
does n number of values means to where the point is connected to (as a chain of the other edges to which this edge is connected to)? example we are provided a node with a chain of numbers (6, 4, 5) where this means we need to generate extra edges which would be connected x times (first one linked to our starting point would be linked to 6 edges, one of them being the starting point)
will edit my answer when I have more information. could you please draw an example in paint and upload it online and provide the link? it would be easier to imagine.
I have a question concerning Abstract Syntax Trees generated with Boost Spirit Library.
I've found many informations about deleting nodes and subtrees in a Binary Search Tree, but I cannot find the same information for ASTs. I have a node in an AS-Tree, and this node is root to a subtree of a complete tree. Now I want to delete the node and all of its children.
I don't know how to do it, and the Boost Spirit Documentation didn't help either.
Has anyone got any tips for me?
The Tree is generated with (Boost 1.46.1):
tree_parse_info<> info = ast_parse(expression.c_str(), parser, skipparser);
And the Expression is something like this:
(variable_17 OR variable_18) AND function( variable_17) <= 30 OR function( subkey_18) <= 30
I use
tree_match<iterator_t>::tree_iterator tree_it = info.trees.begin();
to get the beginning of the tree, and then I do check if one of the subtrees is redundant (doensn't have anything to do with the deleting itself). `Then I traverse through the tree using
tree_match<iterator_t>::tree_iterator children_it = tree_it->children.begin()
and calling the same function with its children (recursive). I can't post the complete code,but that's the most important part of it. I thought, that i can traverse to the leafnodes of a redundant subtree, and set them to null, or something like this. And then I go up the tree again, and delete all other children one after another. However, nothing has worked so far.
An example for traversing the tree: The Traversing
It's the answer.
If I can't delete any nodes, does anyone has an idea, how to create a new tree, based on the existing one, skiping the redundant parts of it.