BFS On a Bipartite graph; Shortest Path between two points - c++

Here's an assumption that I'm making, before I get started, tell me if I am wrong:
Representing a bipartite graph (shown below): I can do this with a nxm matrix where n is one side and m is the other and there's a 1 at the index if they are connected, correct?
Anyways, I'm trying to represent an "erdos" number kind of thing, or a "kevin bacon number" kind of thing, where one side is movies and the other side is actors. So far I have 2 vectors that hold each movie and actor and my adjacency matrix is a matrix of nodes (each nodes contains a movie name, actor name, and adjacency boolean/number), which are 1 if the actor is in that movie and 0 otherwise:
I want to figure out how many degrees of separation there are between two actors (i.e. if actor A was in movie 1, actor B was in movie 1 and 2, and actor C was in movie 2, the degrees between A and C is 2; 0 if the same actor).
My questions are, am I doing it right so far? How do I continue? I know BFS uses a queue but I can't seem to get it right, or even start on the right path. What do I compare? It's like I know what to do but I can't seem to think of it at all. I have two functions which give me the index of the requested actor in the actors vector (and one for the movie), which give me the row and column indices of the adjacency matrix vector, in order to see the node at that index.

Related

Vehicles traversing capacitated streets on a graph

i'm trying to rewrite a discrete optimization problem as a linear/ mixed integer program. But i have problems to convert a capacity constraint.
Suppose we have a graph based on a road-network. The arcs are the streets and the nodes are the intersections of multiple streets. Now we have vehicles traversing the graph. The weights of the arcs represent how long it takes for a vehicle to traverse the arc.
The vehicles and their routes are represented as a sequence of traversed nodes and the corresponding time they arrive at each node.
Now let the arcs be capacitated on how many vehicles can traverse an arc at the same time.
Let the following intervalls be the time when vehicles traverse an arc which takes 2 time units to traverse. The arc also has a capacity of 2:
Example 1: [2,4], [3,5], [2,4]. In this example the capacity is exceeded in the time interval [3,4] as there are 3 vehicles traversing the arc in that time interval.
Example 2: [2,4], [4,6], [3,5]. In this example at no point there are more than 2 vehicles traversing the arc, so the capacity isnt exceeded.
Is there a way to write this as a linear programming restraint?

When adding a vertex to a weighted undirected graph, which weight stays?

I'm doing an adjacency list implementation of a graph class in C++ (but that's kinda irrelevant). I have a weighted directionless graph and I am writing the addVertex method. I have basically everything down, but I'm not sure what I should do when I add a vertex in between two others that were already there and had their own corresponding weights.
Should I just throw away the old weight that the vertex stored? Should I use the new one that was passed in? A mix of both? Or does it not matter at all what I pick?
I just wanted to make sure that I was not doing something I shouldn't.
Thanks!
I guess it depends on what you want to achieve. Usually, an adjacency list is a nested list whereby each row i indicates the i-th node's neighbourhood. To be precise, each entry in the i-th node's neighbourhood represents an outgoing connection from node i to j. The adjacency list does not comprise edge or arc weights.
Hence, adding a vertex n should do not affect the existing adjacency list's entries but adds a new empty row n to the adjacency list. However, adding or removing edges alter the adjacency list's entries. Thus, adding a vertex n "between two other [nodes i and j] that were already there and had their own corresponding weights" implies that you remove the existing connection between i and j and eventually add two new connections (i,n) and (n,j). If there are no capacity restrictions on the edges and the sum of distances (i,n) and (n,j) dominates the distance (I,j) this could be fine. However, if the weights represent capacities (e.g. max-flow problem) you should keep both connections.
So your question seems to be incomplete or at least unprecise. I assume that your goal is to calculate the shortest distances between each pair of nodes within an undirected graph. I suggest keeping all the different connections in your graph. Shortest path algorithms can calculate the shortest connections between each node pair after you have finished your graph's creation.

MST from an array of 2D triangles, but with a little twist

Here's an illustration of the steps taken thus far:
Pseudo-random rectangle generation
"Central node" insertion, rect separation, and final node selections
Delaunay triangulation (shown with previously selected nodes)
Rendering of triangle edges
At this point (Step 5), I would like to use this data to form a Minimum Spanning Tree, but there's a slight catch...
Somewhere in the graph (likely near the center, but not always) will be a node that requires between 3-5 connections to it from other unique nodes. This complicates things, since every other node should only contain a single connection, and the data structures being used make it difficult to determine "what's connected to what" in a solid, traversable format.
So, given an array of triangles in the above format, and a random vertex to use as the "root node", how could I properly traverse the network to create an MST where there are at least 3 connections to our "central node", but no more than 5 connections to it? Is this possible?
Since it's rare to have a vertex in a Delaunay triangulation have much more than 6 edges, you can use brute force: there are only 20+15+6 ways to select 3, 4, or 5 edges out of 6 (respectively), so try all of them. For each of the 41 (up to 336 for degree 9) small trees (the root and a few edges) thus created, run either Kruskal's algorithm or Prim's algorithm starting with that tree already "found" to be part of the MST. (Ignore the root's other edges so as not to increase its degree further.) Then just pick the best one (including the cost of the seed tree).
As for the general neighbor information problem, it seems you just need to build a standard graph representation first. For example, you can make an adjacency list by scanning over all your Edge objects and storing each endpoint in a list associated with the other (in a map<Vector2<T>,vector<Vector2<T>>> or an equivalent based on whatever identifiers for your vertices).
I've taken a workaround approach...
After step 3 of my algorithm, I simply remove all edges which connect to the "central node", keeping track of which edges form the "ring" (aka "edge loop") around it, and run the MST on all remaining edges.
For the MST, I went with the boost graph library.
That made it easy to loop through the triangles I had, adding each of its three edges to an adjacency_list. Then a simple call to whichever boost-provided MST algorithm took care of the rest.
Finally, I readd the edges that were previously taken out. The shortest path is whatever it was in the previous step, plus the length of whichever readded edge that connects to another edge on the "ring" is shortest.
I can then add (or remove) an arbitrary number of previous edges to ensure there are between 3 to 5 edges connecting from the edge loop to the "central node".
Doing things in this order also allows me to know as soon as step 3 if we'll even have a valid number of edges, so we don't waste cycles running a MST.

BGL - determine all mincuts

Given a graph, I want to find all edges (if any), that if removed spilt the graph into two components.
An initial idea would have been to assign a weight of 1 to all edges, then calculate the mincut of the graph. mincut > 1 implies there is no single edge that when removed causes a split.
For mincut == 1, it would have been nice if the algorithm would provide for each mincut the edges it consists of.
Unfortunately, BGL does not seem to support that kind of thing:
The stoer_wagner_min_cut function determines exactly one of the min-cuts as well as its weight.
(http://www.boost.org/doc/libs/1_59_0/libs/graph/doc/stoer_wagner_min_cut.html)
Is there a way to make this work (i.e. to determine more than one mincut) with the BGL or will I have to come up with something different?
This may come a little bit late...
From what I see you only need to find all edges that don't belong to any cycle in the graph(assuming the graph is already connected).
This can be done by iteratively removing leaf nodes(and the edges connected to a them), much like what you do in topological sorting, until there's no leaf node left i.e. every edge in the remaining graph belongs to at least one cycle. All edges removed during the process will be the ones you want.
In pseudocode, for a connected undirected graph G=(V,E), you can do this:
S = Ø
while(there exists a node n∈V s.t. degree(n)==1)
e = edge connected to n
S = S∪{e}
E = E-{e}
V = V-{n}
return S
which can be done in O(|V|+|E|) time

How do I make a NODE GRAPH to use with Dijkstra's Shortest Path?

I am playing around with Dijkstra's Algorithm and have found many sites and code snippets about it and think I would be able to get a grip on it, but I have found no information on how to build the graph itself. Maybe I do not know the correct terms for a google search, but I just cannot find any information on how to build the grpah it self to graph though.
I am making as a learning project, a small c++ Pac-Man game and wish to use this algorithm to control the ghosts that follow pac-man. I have a map (bitmap) and want to place a "node" at each intersection on the maze.
How do I do this? This is the bit I can not understand. How to build the graph itself ?
Is there a visual graph editor maybe? Any advise would be great.
You can think of grids as graphs and search space representations can be shown using graphs:
Block A,B,C,D are nodes of graph and weights between the nodes can represent path distance between nodes.
Graphs can be defined programmatically , the common representations explained below.(Note : For djiksta's algorithm , you would also need to store the weights of the various edges).
Say for example the graph has A connected to B (weight = 5), and B connected to C(weight = 1).
1) Adjacency list : Used to represent the edges as lists and is used more commonly for sparse graphs.
It will have A->B(5) and B->C(1). (It can be promatically represented as an array of linked lists, where each node of the linked list stores the outgoing vertex identification and weight)
2) Adjacency matrix :
It will have a 2 dimensional matrix defined as:
A B C
A 0 5 0
B 0 0 1
C 0 0 0
EDIT : You could find much more detail at this topcoder tutorial series on graphs : section 1 talks about graph representations and section 3 talks about dijksta' algorithm.
It's all abstract. As such, I'll describe how I'm doing graphs in my android game. Ultimately you can define it anyway you want, but here's my implementation.
A little background, the game is a tower defense and the graph represents paths that the enemies walk on as they make their way from a source to a sink. It wouldn't take much for me to write Dijkstra's algo for my model. I have 3 main classes: Graph, Node, and Connection.
The Graph is the main object. It holds a list of Nodes and a list of Connections. This class has methods like addConnection(Node n1, Node n2, int magnitude) (this is how I actually build the graph), getAllSinks(), getAllSources(), and getNeighbors(Node n) (returns all nodes that share a connection with the parameter node). This is probably where a findShortestPath(Node start, Node stop) method would go.
Since it's a game, a Node has the X and Y of its location on the screen. A Node also has a NodeType which is an enum for Source, Sink, and Normal (and other game related uses like towers). The NodeType is not required for dijkstra.
My Connection is a 1 to 1 link from one Node to another Node and it's bi-directional. You could make it directional if you make a distinction between the two Node endpoints, I just don't need to do that in my game. The Connection stores the Weight of the connection. In my case, I weighted my graph as distance from the sources so enemies can always try and take the "heaviest" path to try and make it to a sink, e.g. the end of the path of a tower defense. The weight could be distance or anything you want. This class has methods like getOtherEndpoint(Node n), getBothEndpoints(), and getWeight().
All of these classes are my own construction. They don't inherit from anything. You can build them exactly how you want them and tie any information you need to any piece of the graph. This is just my implementation in Java. You could do the same thing in C++ if you want or if you're inspired to write your own then I won't take it badly.