So if I'm understanding correctly you already have a set for each Integer listing its adjacency? The easiest efficient way I can see to do this is to make use of another Set. Sets are very fast for checking if they already contain values. Set<Integer> adjacent = new HashSet<>(); for...

It seems that for you, vertices v1 and v2 in the example are distinguishable. Then you must make sure that they're distinguishable for the graph as well. In other words, make sure that v1.equals(v2) returns false. You might want to consider adding a member variable "id" (or something) to Vertex,...

algorithm,mapping,openstreetmap,graph-theory,a-star

Have a look into the GraphHopper project (where I'm the author of) or other routing projects for OSM already doing this. The idea is to count the number of ways one node is member of and mark nodes as junctions if they have a count of three or more (or...

python,algorithm,graph-theory,depth-first-search

Here is a working solution that uses two stacks during the iterative subroutine. The array traceBack holds the vertices that have been explored and is associated with complementary 2D-array, stack, that holds arrays of edges that have yet to be explored. These two arrays are linked; when we add an...

Try data.frame(node = V(my_graph)$name, set = membership(clusters(my_graph))) # node set # 1 a 1 # 2 b 1 # 3 c 1 # 4 d 2 # 5 e 2 # 6 f 2 # 7 g 3 ...

I've been doing some extensive work with graphs in python and I'd recommend not using networkx for larger problems. Since the library is pure python it is perfect for smaller graphs and portability, but for larger subgraph isomorphisms I've found that graph-tool works very well. The function call you are...

java,graph-theory,constraint-programming

i managed to find an easier solution to implement than the one proposed by stuXnet. Using Jung library, i check whether there are more than one path available between each pair of a given dependency. If it's the case, then this dependency is certainly needless, so i just have to...

python,algorithm,graph,graph-theory,dijkstra

Dijkstra algorithm always finds the shortest path (in graphs without negative edges) and never backtracks. It is easy to reason about it. Always choosing the minimum Think about a node and its edges (it's just part of a larger graph): 6 _ 3 | / 14| /9 |/ 1-------2 7...

A simple approach would be to keep randomly selecting and removing sets of n nodes until you found a set that doesn't increase the number of components of the graph: remove.edges <- function(g, n) { num.tries <- 0 while (TRUE) { num.tries <- num.tries + 1 g2 <- delete.edges(g, E(g)[sample(seq_along(E(g)),...

c++,boost,graph-theory,boost-graph

We need to know a little more about your graph probably. I had a "similar" problem. This may not be exactly what you are looking for, but it is similar. This is a DFS visitor I used on a directed graph with a root to count the number of paths...

algorithm,graph,dynamic-programming,graph-theory,networkx

If you must go from A to G in an efficient way, you aren't looking for a minimum spanning tree algorithm. A simple shortest path algorithm is enough. You just have to adapt you graph to put the weights in the edges instead of the nodes. But it's just a...

algorithm,graph-theory,dijkstra,np-complete,hamiltonian-cycle

No, this is not possible. Your simplified problem is still NP-hard. A reduction from travelling salesman: Given a graph (V, E), find the shortest path that visits each v in V exactly once. Take an arbitrary vertex v in V. Split v into two vertices v_source and v_sink. Use your...

python,dictionary,graph-theory

Note that you're linking the networkx documentation of version 1.6 whereas the current version is 1.8.1. I recommend rather thinking about what type of graph you need, i.e., single undirected edges between your nodes, choose a networkx.Graph, multiple directed edges, choose a networkx.MultiDiGraph (DiGraph and MultiGraph also exist). You can...

algorithm,binary-search-tree,graph-theory,breadth-first-search

For a 'proper' tree (see below), it's the same thing, at least by most definitions. Like Wikipedia, for example: Breadth-first See also: Breadth-first search Trees can also be traversed in level-order, ... ... a breadth-first (level-order) traversal ... Well, at least level-order traversal is the same as breadth-first traversal. There...

matlab,graph,plot,graph-theory,graph-visualization

If you want the links to be directional, and have the Bioinformatics toolbox, you can create a biograph object. This also allows for labelling the nodes with identification strings if you so desire, see the help file. If not they'll be called "Node 1", "Node 2", etc. You'll need to...

python,hadoop,graph-theory,apache-spark

It looks like the python bindings to GraphX are delayed at least to Spark 1.4 1.5. It is waiting behind the Java API. You can track the status at SPARK-3789 GRAPHX Python bindings for GraphX - ASF JIRA...

java,algorithm,recursion,binary-search-tree,graph-theory

The algorithm you described is not acceptable because there can be at most 100 rows, so if in each row the number of nodes in the tree doubles, you'll end up with 2^101 nodes in your tree in the worst case. That problem can be solved by a simple dynamic...

The general methods for finding all connected components of a graph are Breadth-First-Search or Depth-First-Search. SAS is not the best tool for implementing such algorithms since they require using such data structures as queues. Still it can be done with hash objects. Here's the code for BF-search. data people; input...

An "index" or "position" of a node has nothing to do with the graph itself. It only has to do with how you have chosen to store the graph. The number you have on each node is just a label, which could be anything. Whether or not the numbers 0...

algorithm,graph-theory,bipartite

Let's decompose the problem. Your graph is actually a set of connected components, each connected component is (U_i,V_i,E_i). To maximize the number of edges, you need to maximize the value of |X|*|Y| To get the maximal value of |X|*|Y|, you obviously need to use all vertices (otherwise, by adding another...

Your algorithm seems correct, and will indeed find if e is participating in all unweighted-shortest paths. Proof: If e is in all shortest paths -> removing e will negate all this paths -> the new shortest path will be longer than the old one -> the algorithm yields the correct...

python,algorithm,graph,graph-theory,networkx

Wait if the graph is actually a representation of a city, then there's one embedding of it, already. Just take t the faces of that embedding. You can't remove one face (ie. It's minimal) and the minimal cycle base is unique (first lemma of the paper you cite), so there's...

algorithm,theory,graph-theory,spanning-tree

You can just mark a vertex as visited when you push it to the stack, not when you pop it.

The cycle is called Eulerian, iff it contains all edges, exactly one time each. That means that Eulerian cycles can only differ by edge's order (I propose to exclude edge's cyclical permutations as trivial option). It is possible to find Eulerian cycle, using Fleury's algorithm: in short, move as you...

algorithm,graph,graph-theory,discrete-mathematics,minimum-spanning-tree

Yes, the algorithm always finds a spanning tree (if such exist, i.e. the graph has a source). Not sure if it finds a minimal spanning tree though. You have already proven there are no cycles in the resulting graph, so we only need to show connectivity. Proof that the resulting...

matlab,matrix,octave,graph-theory,adjacency-matrix

One way would be to write your own algorithm using some sort of electrostatic repulsion as in the paper you linked. Can probably be done in less than 40 lines of Matlab (it seems others have tried). But sometimes, it is better to use external tools than to do everything...

algorithm,complexity-theory,theory,graph-theory

I get the impression from papers like http://research.microsoft.com/pubs/144985/todsfinal.pdf that there is no algorithm that does better than O(VE) or O(V^3) in the general case. For sparse graphs and other special graphs there are faster algorithms. It seems, however, that you can still make improvements by separating "index construction" from "query",...

graph,neo4j,graph-theory,giraph

Yes it is possible, e.g. imagine your nodes have a numeric value property: MATCH (n:Label) WITH abs(n.value-{new_value}) as delta,n ORDER BY delta DESC LIMIT 1 CREATE (m:Label {value:{new_value})-[:LINKED]->(n) ...

algorithm,tree,graph-theory,graph-algorithm

There are 13^11 ~ 1.8e12 spanning trees on 13 nodes, so brute force is out of the question. I believe that the intended solution is dynamic programming. For each pair comprised of a nonempty subset of nodes and a distinguished node belonging to the subset (the root), compute the optimal...

Your problem is pretty straight forward. In your create function you try to iterate over the adjacency lists however you continually index the n-th headnode which you probably know is outside the bounds of the array. You pass in 3 as nodes and assign it to n and in your...

java,algorithm,search,graph-theory,adjacency-matrix

You don't extract the shortest path correctly. You are adding every node you process to the shortest path. If you want to use BFS to find the shortest path, you have to keep track of the shortest path to every intermediate node by storing "back edges" and only in the...

c++,algorithm,graph-theory,connected-components

Let's take a look at how many edges are created in the worst case. It is N * (MAX_R - MIN_L), which is 10^5 * 2000 under given constraints. You program runs out of memory and gets runtime error. A more efficient algorithm is required. Here is a simple solution...

r,graph-theory,igraph,shortest-path

I know that my title doesn't fully account for what my question really was. So I'm answering it myself since I just got it to work. #Mean local efficiency (global efficiency for each node) gn<-graph.neighborhood(my.graph,1) #list with subgraphs of directly connected graphs names(gn)<-V(my.graph)$name local.eff<-numeric(length(gn)) for (i in 1:length(gn)){ gn[[i]]<-gn[[i]] -...

algorithm,optimization,graph-theory,traveling-salesman

Safe Moves Here are some ideas for safely mutating an existing feasible solution: Any two consecutive stops can always be swapped if they are both pickups, or both deliveries. This is obviously true for the "both deliveries" case; for the "both pickups" case: if you had room to pick up...

When there are no dependencies, this is the NP-hard bin packing problem. Bin packing has some clever exact algorithms, but I'm not sure how to adapt them, and they're hard to implement anyway. Here's an analog of the pretty good First Fit Decreasing approximation (11/9 asymptotic approximation ratio for the...

I believe that you are referring to the Clique problem.

java,algorithm,arraylist,graph-theory,depth-first-search

I will assume that you have a State class with the following attributes (if you like graphs, use Node instead of State): Set<Town> unused; // towns not yet visited ArrayList<Town> path; // current path double dist; // total distance in path Then use code like this one to recursively try...

No. Having a node connected to all three nodes in a triangle (which is just a more complicated way of saying "it has a clique of size 4") is sufficient but not necessary for the graph to not be 3-colorable. Graphs may be not 3-colorable for different reasons than having...

Example 1: From your graph: (0,2),(0,3),(1,2),(1,3) 2 / \ 0 1 \ / 3 K(0, 1) Create a tree like this: 0 / \ 2 3 / \ 1 1 Each branch begins at 0 and ends at 1. If a branch does not reach 1, it's not included. Remove...

You don't need to 'cut' the graph. All you need to do is split the current image in 2 sets, A and B with A = y_1(i) > t and B = y_1(i) <= t where y_1 refering to your algorithm is the second smallest eigenvector (also the solution for...

algorithm,graph,graph-theory,graph-algorithm,dijkstra

I think your approaches are actually equivalent, provided that for approach #1, you record only the shortest distance to each node for each number of red edges used -- you don't need to record the entire path (just as you don't need to record it for ordinary Dijkstra on an...

algorithm,graph,graph-theory,minimum-spanning-tree

Note that |E| >= |V|. Choose any vertex, mark it as component1, iterate each connected vertex (along MST edges) and mark component1 as well. That's O(|V|). Find a vertex from the other component by scanning until not marked. That's O(|V|) again. Iterate each vertex in 2nd component (along MST edges),...

You can find articulation points using a modified depth first search - see http://en.wikipedia.org/wiki/Biconnected_component. An articulation point of a graph is a node that, if removed, disconnects the graph. Every graph can be split up at the articulation points into biconnected components. If you are lucky, you just need to...

algorithm,search,graph-theory,graph-algorithm,breadth-first-search

The Example Let G = (V,E) a graph with V = ℕ ∪ {-1, 0} and E = { {-1,t}, {t,0} | t ∈ ℕ } and let s = -1 and f = 0. There exist an infinite number of paths of length 2 from s to f, but...

It's just a question of difference in algorithm. If you do it recursively, you would iterate 2 completely before you backed up to 3, hence 1->2->4->5->3. If you do it iteratively, you'd visit the neighbors in opposite order, so you'd end up iterating 3 completely first, hence 1->3->2->5->4. Your algorithm...

algorithm,graph,go,graph-theory,graph-algorithm

The redundant permutations are filtered out because the start node of each returned permutation is always less than all the remaining elements (under some ordering). I suspect the problem is in a missing implementation of these steps: AK:= adjacency structure of strong component K with least vertex in subgraph of...

java,arrays,algorithm,graph-theory,adjacency-matrix

Try this: static void set(boolean[][] aM, int cols, int row0, int col0, int row1, int col1) { int index0 = row0 * cols + col0; int index1 = row1 * cols + col1; aM[index0][index1] = aM[index1][index0] = true; } static boolean[][] adjacencyMatrix(char[][] cA) { int rows = cA.length; int cols...

algorithm,theory,graph-theory,weighted

This is an NP-hard optimization problem. For example, the Partition problem can be reduced into this easily (the planarity property does not cause a problem). So an algorithm that calculates an optimal solution (and you seem to ask for an optimal solution in your comment) is unlikely to be practical...

python,numpy,random,graph-theory,igraph

Having done a bit of reading, it looks as though the best solution might be the generalized version of Gleeson's algorithm presented in this paper. However, I still don't really understand how to implement it, so for the time being I've been working on Bansal et al's algorithm. Like my...

I would proceed by iterating over the addresses. For each address, find its fellows/neighbors and give them all have the same entity ID. The mapping from address to entity can be stored in a separate table and mapped onto the transactions table after the loop is finished. setkey(DT,Address) AE <-...

algorithm,graph-theory,path-finding,a-star

It might be possible yes, but A* is a popular algorithm for finding shortest paths in grid like graphs. For graphs in general there are a lot of other algorithms for shortest path calculation which will match your case better. It depends on your setting which one to use. If...

java,algorithm,graph,graph-theory

You're describing the minimum cut problem. It's equivalent to finding the maximum flow, and the Ford Fulkerson algorithm can find it.

algorithm,graph-theory,graph-algorithm,shortest-path

I think you might consider a dynamic programming approach. At iteration 0, let s_0 = {(origin_0, origin_1)}. For iteration k+1, let s_k+1 = {(x,y) | x != y, exists an (prev_x, prev_y) in s_k s.t. e(prev_x, x) in E and e(prev_y, y) in E}. This should proceed forward with |s|...

python,graph-theory,depth-first-search

As mentioned in the comment, your algorithm has no reason to terminate if you allow arbitrary cycles. What you could do is allow for a maximum path length and dismiss all paths that are too long: def find_all_paths(graph, start, end, path=[], max_length=10): if len(path) >= max_length: return [] path =...

Just because each node goes to only one other node, does not make it any less a graph. Just a degenerate case of a graph. You still have the node properties and the arc properties of each connection.

algorithm,graph-theory,minimum-spanning-tree

It is possible to solve this problem efficiently(in O(n log n) time), but it is not that easy. Just using the Prim's algorithm with a heap does not help(it actually makes it even slower), because its time complexity is O(E log V), which is O(n^2 * log n) in this...

neo4j,relationship,graph-theory,graph-databases

This query will return you the first part of your answer : MATCH (k:Keyword) WITH k LIMIT 1 MATCH (k)<-[:HAS]-(a) WITH k, collect(a) as artefacts WITH k, artefacts, size(artefacts) as c UNWIND artefacts as artefact MATCH (k)<-[:HAS]-(artefact)-[:HAS]->(k2) RETURN c, artefacts, collect(distinct(k2.name)) as keywords, count(distinct(k2.name)) as keyWordsCount However, I guess you...

python,algorithm,tree,graph-theory,clique

To construct a non-nice (in general) tree decomposition of a chordal graph: find a perfect elimination ordering, enumerate the maximal cliques (the candidates are a vertex and the neighbors that appear after it in the ordering), use each clique as a decomposition node and connect it to the next...