LeetCode160-Intersection of Two Linked Lists - singly-linked-list

This is the first example of the intersection of two linked lists on LeetCode webpage.
The first linked list, A, is [4,1,8,4,5], the second one, B, is [5,6,1,8,4,5]. I found the intersection part of both linked lists is [1,8,4,5]. But the official explanation said "The intersected node's value is 8. From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B."
Can anyone explain that why the started node of the intersection is "8" instead of "1" in this case?
Thanks a lot!

The image provides important context (taken from https://leetcode.com/problems/intersection-of-two-linked-lists/):
You're looking for the point where the two lists start to intersect - this depends on the node connections, not their values. The "1" in both A and B do not imply that they intersect, as the image shows.

i had this same doubt previously, the problem was I was trying to compare the values of nodes, lets say nodeA with a value of 1 and another nodeB with also a value of 1 the problem is if we just compare the nodes in terms of their values we are ignoring the other factors of node like its address, other next elements in node its length, etc. So, instead of matching in terms of nodeA.val == nodeB.val we must be matching in all aspects of a node that is nodeA == nodeB. As shown below:
while node1_to_use is not None and node2_to_use is not None:
if node1_to_use == node2_to_use: # ignore doing this node1_to_use.val == node2_to_use.val
return node2_to_use
node1_to_use = node1_to_use.next
node2_to_use = node2_to_use.next

Related

minimum number of nodes that traverse entire graph

Note: The question is entirely changed.
In the following graph, we can traverse entire graph if we select the nodes 0 and 2. I am looking for an efficient algorithm which returns this two nodes. Note that this is neither vertex-cover problem nor dominating-set problem since we don't need to select node 3. We say that, if we select node 0, we can go to node 1 from there and if we select node 2, we can go to node 3 and then node 4 from there.
If I run a SCC algorithm on it, it finds all vertices as a different SCC and I can't go from there to anywhere:
C:\>project2 ../../input.txt o.txt
Following are strongly connected components in given graph (Each line is a different SCC)
2
4
3
0
1
If there is no cycle in the graph i.e. the graph is a Directed Acyclic Graph (DAG), then we just need to count the indegrees for each node. The set of nodes with indegree 0 is the required set.
In case you are not familiar with indegree, if there is an edge a->b then indegree of b increases by 1.
This works because, if there is an edge a->b i.e. b has an indegree it means there is a node a from which b is reachable. So it is always better to include node a to the set instead of b. A node with indegree 0 has no other way to get visited unless we start with the node itself. So it will be included in the set.
In case there is a cycle in the graph, we search for Strongly Connected Components(SCC). Then we have build a new graph considering a SCC as one node and add edges from initial graph which connect two different SCC's. The new graph will be a DAG. Then we can apply the above procedure to find the required set of nodes.

Find all possible paths in depth first search in 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.

How to create directed graph with nodes having multiple data?

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.

Many edges to a single node in graphs in c++

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.

How to find all clusters of forest on map?

How to find all clusters of forest on map ?
I have simple class cell like (Type is enum {RIVER, FOREST,GRASS,HILL}
class Cell{
public:
Type type;
int x;
int y
};
and map like vector<Cell> grid. Can anyone suggest me algorithm to create list<list<Cell>> clusters where list contains FOREST cells in same cluster (cluster are set of connected cells - connection can be in eight direction:up,down,left,right,up_right,up_left,down_left,down_right)? I need to find all clusters of forest on map and put every single cluster in list<Cell>.
The algorithm is rather simple and it actually doesn't even depend on the exact definition of what a cluster is. Say you have a predicate cluster(f0, f1) which yields true if f0 and f1 are in the same cluster. All you need to do is to run though the grid and find a forest. If a cell f is a forest, you check if cluster(f, other) for each known forest. If cluster(f, other) yields true you add f to the cluster of other. You continue to check other known forests in other clusters: when you find another cell c in another cluster for cluster(f, c) also yields true, you merge (std::list<Cell>::spice()) the two clusters.
I had put this as a comment, but may as well answer:
Look up the union-find algorithm. Using path compression, you can just
walk through the structure afterwards and create a list for each root,
adding your cells to the appropriate list as you go.
Link: http://en.wikipedia.org/wiki/Disjoint-set_data_structure
For all your cells, perform a union with the cell above and to the left. If you want diagonals to join, then also include the top-left and top-right diagonal).
Use the path-compression version of union-find so that all nodes in a cluster point to a single root. Then all you have to do is walk through your structure (after doing all the unions) and add nodes as you go. Pseudo(ish)code:
foreach node
Find(node) // this ensures path compression
if not clusters.hasList(node.root)
clusters.createList(node.root)
end
list <- clusters.getList(node.root)
list.append(node)
end
The above assumes that if a node is a root, then node.root points to node.