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-algorithm

Here is a faster solution: Let's find paths that contain the smallest number of black cells. We can use 0-1 breadth-first search. An edge that leads to a white cell should have a weight 0 and an edge that leads to a black cell should have a weight 1. There...

You apply the Dijkstra algorithm the normal way and the shortest path from a to c is really 3. However, you should read the pseudocode for Dijkstra to understand that table. Firstly, Dijkstra returns an array (or another data structure, depending on implementation, for our purposes just say it's an...

c++,algorithm,graph-algorithm,disjoint-sets,union-find

MAKE-SET(v) means that you're initializing a set consisting of only the vertex v. Initially, each vertex is in a set on its own. FIND-SET(u) is a function that tells you which set a vertex belongs to. It must return a pointer or an ID number that uniquely identifies the set....

Your problem is easily reduced to a well-known minimum-cost flow problem: The minimum-cost flow problem (MCFP) is to find the cheapest possible way of sending a certain amount of flow through a flow network. This reduction can be done the following way. Add a dummy "source" and "sink" vertices to...

algorithm,language-agnostic,graph-algorithm

What you are looking for is called the minimum cut of a graph. By the Max-flow_min-cut_theorem the value of the minimum cut is equal the the value of the maximum flow. Computing the maximum flow in a network is a standard problem and there are several algorithms for computing this...

algorithm,graph,graph-algorithm

The Brandes' algorithm gives the exact centrality of each vertex. I don't know which implementation of the algorithm is used in Sage, but chances are that it's a precision problem. The accumulation part of the algorithm is probably the trickiest. When you reach that part, you have in sigma...

python,algorithm,graph-algorithm,hamming-distance

Assuming you store your dictionary in a set(), so that lookup is O(1) in the average (worst case O(n)). You can generate all the valid words at hamming distance 1 from a word: >>> def neighbours(word): ... for j in range(len(word)): ... for d in string.ascii_lowercase: ... word1 = ''.join(d...

algorithm,graph-algorithm,approximation

Here's a program written in Python that walks all potential paths. It uses recursion and backtracking to find the paths, and it marks a grid to see which locations are already being used. One key optimization is that it marks the start and end points on the grid (10 of...

algorithm,data-structures,graph-algorithm,nearest-neighbor,point-clouds

Your problem is part of the topic of Nearest Neighbor Search, or more precisely, k-Nearest Neighbor Search. The answer to your question depends on the data structure you are using to store the points. If you use R-trees or variants like R*-trees, and you are doing multiple searches on your...

algorithm,graph,graph-algorithm,directed-acyclic-graphs

Let's assume that f(i, j) is the number of paths from i to j vertex. Initially(I assume that the graph is empty, if it is not the case you can add all edges using the add operation) f(i, j) = 1 if i = j and 0 otherwise. To add...

algorithm,graph,graph-algorithm

The problem you're describing ends up being NP-hard (via a reduction from the longest path problem), so unless P = NP there aren't going to be any algorithms that are correct on all inputs and efficient on all inputs. You'll either need to be willing to accept answers that aren't...

algorithm,language-agnostic,graph-algorithm

Tarjan algorithm for searching strongly connected components of a directed graph http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm allows you to make the distinction you need.

algorithm,graph-algorithm,dijkstra,bellman-ford

Yes, it will give the same results. It will run slower, though, as it could also have been used for graphs with negative edges (subject to the absence of negative cycles). If you look at the proof of BF's correctness, there is no assumption there that some of the edges...

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

The problem you're trying to solve is called the maximum independent set problem applied to trees. As a hint, think about the following: For each complete subtree of the tree, think about the optimal solution for that subtree in two cases - the case where you include that node in...

algorithm,graph-algorithm,bellman-ford

Sort a shortest path tree topologically.

algorithm,social-networking,graph-algorithm,sampling,directed-graph

You can treat the undirected graph like a directed graph for the purposes of sampling. Any sampling strategy for a directed graph should work assuming it allows cycles. You simply want to sample the nodes and edges, so any edges that become part of the sample just accept the edge...

Actually this is not an easy question. In general you need to match the communities in the two graphs, using some rule or criteria that the matching optimizes. As you can have different number of communities, the matching is not necessarily bijective. There were several methods and quantities proposed for...

algorithm,graph,graph-algorithm,minimum-spanning-tree,degrees

To summarize the suggested algorithm [with tightened requirements on epsilon (which you called x)]: Pick a tiny epsilon (such that epsilon * deg(u) is less than d, the smallest non-zero weight difference between any pair of subgraphs). In the case all the original weights are natural numbers, epsilon = 1/(deg(u)+1)...

They don't have to be connected. Just throw in some loose nodes. Those nodes are just there to fix the number of colours, they shouldn't be affecting colourability. You have to add more than just 1 or 2 (which would be enough to get a multiple of 3) in general....

algorithm,graph,graph-algorithm

If you allow preprocessing, there is a fast method: Construct the bridge-block forest, whose vertices are 2-connected components, and whose edges are bridges. (It's a tree if the graph is connected.) When you add an edge, if this connects points in the same 2-connected component, nothing happens. If you connect...

algorithm,graph,graph-algorithm

You can use a maximum flow algorithm to compute the minimum cut between A and B in your graph. Runtime: O(n*m) with an excess-scaling push-relabel variant (since you have only unit capacities). Your solution is O(2^m * (n + m)) if you use DFS or BFS for reachability in the...

algorithm,graph,graph-algorithm,flow,edge

I believe this should work: For every edge, add a reverse edge with infinite capacity. That way if the min-cut is finite, original edges can only go from S to T, not the other way round.

java,vb.net,algorithm,graph-algorithm

For your problem, I think BFS still works. Using BFS to solve traditional Maze problem, starting from the beginning point, you have to: 1. Enqueue every point that is accessible (not a piece of wall, and not visited) and connected to the current point. 2. Dequeue current point and mark...

You can run a BFS from your node s as starting point, this will give you a BFS-tree. Afterwards you can built a lowest-common-ancestor (LCA) data structure on this BFS-tree. This can be done for example with Tarjan's lowest-common-ancestor algorithm. I will not got into details here. Given two nodes...

algorithm,graph-algorithm,independent-set

In any graph, the complement of an independent set is a vertex cover and vice versa, so your problem is equivalent to finding the minimum weight vertex cover in the graph. The latter can be solved using maximum flow techniques: Introduce a super-source S and a super-sink T. connect the...

java,data-structures,tree,graph-algorithm,depth-first-search

You don't need stack here. Only recursion: public void dfs(Node node) { if (node == null) { return; } System.out.println("Node: " + node.getVertex()); node.state = State.Visited; for (Node n : node.getAdjacent()) { if (n.state != State.Visited) { dfs(n); } } } UPDATE To check path existence: public boolean isPath(Graph graph,...

algorithm,graph-algorithm,pseudocode

The recursive version is given in Wikipedia as this: BronKerbosch1(R, P, X): if P and X are both empty: report R as a maximal clique for each vertex v in P: BronKerbosch1(R ⋃ {v}, P ⋂ N(v), X ⋂ N(v)) P := P \ {v} X := X ⋃ {v}...

algorithm,graph-algorithm,tile,hexagonal-tiles

Let's set up a coordinate system where the hex with coordinates (i,j) is adjacent to (i-1,j), (i-1,j+1), (i,j-1), (i,j+1), (i+1,j-1), (i+1,j). (0,3) (2,2) (4,1) (1,2) (3,1) (0,2) (2,1) (4,0) (1,1) (3,0) (0,1) (2,0) (1,0) (0,0) I'm going to apply a shear transform so that I can draw hex grids compactly...

algorithm,graph,tree,graph-algorithm

The core of your question seems to be what makes finding an MST (technically called an optimum branching or minimum-cost arborescence) in a directed graph different and therefore harder than finding an MST in an undirected graph. Both Prim's and Kruskal's algorithms work because of the cut property. If G...

scala,network-programming,apache-spark,graph-algorithm,spark-graphx

I think you want to use GraphOps.collectNeighbors instead of either mapReduceTriplets or aggregateMessages. collectNeighbors will give you an RDD with, for every VertexId in your graph, the connected nodes as an array. Just reduce the Array based on your needs. Something like: val countsRdd = graph.collectNeighbors(EdgeDirection.Either) .join(graph.vertices) .map{ case (vid,t)...

c++,graph,graph-algorithm,topological-sort

First, for the number of edges, it would be simpler to count them directly when you build the graph (just add a counter in your Digraph class and increment it each time you add an edge … ) For the topological sort, first I have a question: your edges are...

java,algorithm,code-review,graph-algorithm,path-finding

First of all, you are mostly on track. I strongly suspect the code you posted is still under development and has some problems. But, still your assumption of distance is positive is not correct in general. A* is a graph search algorithm and edges can have negative weights as well...

algorithm,tree,binary-tree,binary-search-tree,graph-algorithm

I guess this should do the trick: traverse(BinaryTree *root) { if (!root) return; cout << p->data << " "; if (root->left ) traverseL(root->left ); //special function for outer left if (root->right) traverseR(root->right); //special function for outer right } traverseL(BinaryTree *p) { cout << p->data << " "; if (root->left )...

algorithm,random,graph-algorithm,overlap

Here is the description of an algorithm that finds an optimal envelop for image sprites. You can easily bound it to your container side. Then as per my comment: find all the center points of your rectangles, and enlarge those points from the middle of the container by a ratio...

java,algorithm,graph,graph-algorithm

You may just need this test: boolean isCutRoot(Vertex root) { final Edge[] rootEdges = graph.incidentEdges(root); return rootEdges != null && rootEdges.length >= 2; } However, if it is possible for multiple edges from the root to point to the same vertex, you need to modify the above method to check...

python,web-crawler,graph-algorithm,pagerank

It was the edge adding function that ruined it all. Fixed it to: def update_graph_links(): """register each node with neighbours pointing at it""" global pr_nodes for node in pr_nodes.itervalues(): for u in node.links_to_node: if u in pr_nodes: pr_nodes[u].links_from_node.add(node.url) return After a few adjustments, some refactoring and adding proper comments it...

algorithm,graph-algorithm,discrete-mathematics,proof

Disclaimer: I don't know how much formal you want your proof to be and I'm not familiar with formal proofs. induction on the while loop: Is it true at the beginning? Does it remain true after a step (quite simple path property)? same idea, induction on k (why k+1???): Is...

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

Switch 4 : Toggles all numbers that have modulus 1 with 3 1 % 3 = 1 4 % 3 = 1 7 % 3 = 1 10 % 3 = 1 Switch #1: 0000000000 <- Switch #2: 0101010101 <- Switch #3: 1010101010 Switch #4: 0110110110 <-...

algorithm,graph,graph-algorithm,shortest-path

Here is a simple solution: Sort the edges by their weights. Start adding them one by one(from the lightest to the heaviest) until X and Y become connected. To check if they are connected, you can use a union-find data structure. The time complexity is O(E log E). A proof...

There are ways to solve this problem fully online, but they're more complicated than this answer. The algorithm that I'm proposing is to maintain a spanning forest of the available edges, together with the number of components of the spanning forest (and hence the graph). If we were attacking this...

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...

No, there is no algorithm better then O(n2). The algorithm will need to at least go over each pair. There are O(n2) possible pairs in the graph: . Therefore the algorithm bottom boundary is = O(n2)....

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...

algorithm,math,graph-algorithm

You can use a dynamic programming approach. The sketch of a recurrence is: M(0, 1) = 1 M(t, n) = T(t-1, n-1) + T(t-1, n) + T(t-1, n+1) Of course you have to consider the border cases (like going off the board or not allowing to exit the end of...

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...

algorithm,graph,graph-algorithm

Given the conditions in the question (that is, the only edges in the graph are part of the cycle), the length of the cycle is the number edges in the graph, which is half the number of 1s in the adjacency matrix (each edge (i, j) appears twice in the...

c#,algorithm,swift,coordinates,graph-algorithm

Here is an example I come up with: (tested in a Playground with Swift 2 Xcode 7 beta 2) struct Point{ var x, y: Int init(_ x: Int, _ y: Int) { self.x = x self.y = y } /** get points around it (Xs around P) if all {...

java,r,algorithm,geospatial,graph-algorithm

I would do it like this: may be some 2d array point grouping to match the grid that should speed up all the following operations. compute average grid sizes (img1 from left) as two vectors create blue points (img2) as: gray_point (+/-) 0.5*blue_vector create red points (img3) as: blue_point (+/-)...

You can have each node maintain a list of dependent nodes and also a "dirty" flag. Then whenever a node changes, recursively set the dirty flag on every dependent node. (If a node is already marked dirty, don't recurse.) You can then make a second pass to re-evaluate each dirty...

algorithm,graph,graph-algorithm

This problem is NP-Hard as well, and is known as maximum independent set problem. A set S<=V is said to be Independent Set in a graph if for each two vertices u,v in S, there is no edge (u,v). The maximum size of S (which is the number you are...

algorithm,graph,artificial-intelligence,graph-algorithm,maze

Well, it is hard to say anything for sure without knowing more details, but for most of the shortest path search algorithms it is fine not to create any nodes for cells that contain a wall at all.

java,algorithm,graph,graph-algorithm

You can also use adjancy list using the following code snippet - int n; List<Integer>[] adj; AdjacencyLists(int n0) { n = n0; adj = (List<Integer>[])new List[n]; for (int i = 0; i < n; i++) adj[i] = new ArrayStack<Integer>(Integer.class); } Then add edge using the function - void addEdge(int i,...

graph,graph-algorithm,arangodb

You can simply pass the same set of vertices as both parameters for common neighbors. Then repack the result in a better format for AQL to compute the intersection: let res = ( let nodes = ["a/A","a/B","a/C"] for n in GRAPH_COMMON_NEIGHBORS("g",nodes , nodes) for f in VALUES(n) return VALUES(f) )...

python,for-loop,optimization,comparison,graph-algorithm

You can iterate through pairs using itertools.combinations for pair in itertools.combinations(d['people'], 2): first, second = pair if first[0] == second[0]: g.connectThem(first, second) These are the pairs that are produced from combinations [('John', 'Carry'), ('John', 'Joe'), ('John', 'Greg'), ('John', 'Carl'), ('John', 'Gene'), ('Carry', 'Joe'), ('Carry', 'Greg'), ('Carry', 'Carl'), ('Carry', 'Gene'), ('Joe',...

algorithm,graph,graph-algorithm

To get an overall result I'll report what I did. I implemented the in the question mentioned algorithm. (Lets call it thigg's algorithm, because noone mentioned a name) Thigg's algorithm: for each node in the graph: if there is a path from src to this node and a path from...

algorithm,graph,time-complexity,graph-algorithm,shortest-path

This can be solved in time O(nm + n2 log n) by running Dijkstra's algorithm on an appropriately-constructed graph. To motivate the intuition for where we're going, let's assume for now that the optimal path makes at most one color change and starts by following a red edge. The path...

algorithm,time-complexity,graph-algorithm

If you can find all strongly connected components in the linear O(V + E) time requested then you are done. This may seem a bit overkill but it solves the problem. To find all strongly connected components, assuming your graph is represented as an adjacency list, perhaps the simplest O(V...

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|...

algorithm,tree,graph-algorithm

Create a recursive function that does a post-order traversal of the tree. The function returns the subtree size and a vertex, or the vertex can be global (in which case you just set it instead of returning it). Call the function for the root. Call the function on each child's...

javascript,angularjs,graph-algorithm

It is called Hamilton cycle problem. Or travelling salesman problem. https://en.wikipedia.org/wiki/Travelling_salesman_problem...

python,algorithm,dictionary,graph-algorithm,dijkstra

Dijkstra's algorithm solves the single-source shortest-path problem. Given a graph and a vertex in the graph, it finds the shortest path to every other vertex. If you want your implementation to run fast, you must use a priority queue. It's fine to use a dictionary to represent the graph initially,...

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

I would suggest you to do something like the second answer in the given question: This is prim's algorithm : Start by picking any vertex to be the root of the tree. While the tree does not contain all vertices in the graph find shortest edge leaving the tree and...

algorithm,graph-algorithm,matching,scilab

I do not know Scilab I am afraid, but if you are willing to use Python it is very easy as the Networkx library provides support for this function: import networkx as nx import networkx.algorithms.matching as matching def C(i,j): return i*j n=40 G=nx.Graph() for i in range(n): for j in...

java,algorithm,data-structures,graph-algorithm

The approach that comes to mind could be to keep an ordered list of the orders and perform a binary search for the limit amount. All orders before that point in the ordered list will be less than the limit amount. // Generate a random array of numbers Random r...

algorithm,math,graph,dynamic-programming,graph-algorithm

To my understanding, the problem can be solved as a Maximum Bipartite Matching, however the modelling requires the graph to be relatively large compared to the original input; for every feasible edge (s_i,b_j) introduce s_i nodes for the producer partition and b_j for the consumer partition and connect each producer...

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-algorithm

You can use an adjacency matrix to store graphs with multi-edges. You just let the value of c[i][j] be the number of times that vertex i is adjacent to vertex j. In your first case, it's 1, in your second case, it's 3. See also Wikipedia -- adjacency matrices aren't...

java,graph-algorithm,priority-queue,comparable

To satisfy the sorting capability of the PriorityQueue class (used by UniformCostSearch), your Node class must implement the Comparable interface, not the Comparator interface. To use the node parent in your comparison, you might try this: @Override public int compareTo(Node that) { if (this.parent != null && that.parent != null)...

algorithm,graph,graph-algorithm,linear-programming,np-complete

It's possible to formulate this as the following problem. Suppose each vertex v in the graph has weight w(v). You define a variable x(v), and use some out-of-the-box linear programming solver to solve max \sum_v w(v) x(v) (maximize the weight of chosen vertices) subject to x(u) + x(v) <= 1,...

c,algorithm,graph,graph-algorithm

Do you mean constant or linear? If you mean linear: Why not take the differences of adjacent values and search for a sequence that stays close to constant? If you mean constant: Why not take the differences of adjacent values and search for a sequence that stays close to 0?

python,algorithm,dictionary,graph-algorithm,dijkstra

You can still use a heap even if it requires a list. graph.keys() returns a list of keys in your dictionary. The heap can then be built using the keys and if you need to find vertexes, dictionary lookup can be used. vertexes = graph[heap.pop()]....

That's a somewhat muddled editorial. Let's focus on creating 0-interesting graphs first. The key fact from graph theory is the following formula. sum_{vertices v} degree(v) = 2 #edges In a graph where every vertex has degree 4 (4-regular graph), the left-hand side is 4n, so the number of edges is...

algorithm,graph,graph-algorithm,path-finding,bellman-ford

Just reverse all the edges, and treated destination as start node. Problem solved.

java,oop,design-patterns,graph-algorithm

It does feel a bit like a flavor question. If I understand correctly you have data driven flow , by which I mean you have some data (in this case in form of xml's and scripts) that dictates what actions will be taken (so it's not known at compile time,...

algorithm,search,data-structures,graph-algorithm

If you take a classic BFS algorithm and replace the FIFO queue with a LIFO stack, you will indeed get DFS vertex discovery order - so called DFS pre-ordering. I.e. the order in which your algorithm will visit graph vertices for the very first time will be exactly the same...

r,algorithm,graph,network-programming,graph-algorithm

Given the set Sn of all n-tuples of connected node subsets, construct the set of all n+1-tuples of connected node subsets by iterating over all s={a1,a2,...an} and there iterating over all ai to find a connected node ax which isn't in s. Build s'={a1,a2,...an,ax} and add to Sn+1 (which, as...

algorithm,graph,computer-science,graph-algorithm,dfs

Step 0: If there is no path from v to t, then answer is NO. Step 1: Make the graph G' after collapsing all the strongly connected components of G. Step 2: If the vertex 'v' is a part of some SCC consisting of more than 1 vertex, then there...

algorithm,graph,graph-algorithm

So after this experience, I found that you should look into the ant colony algorithm and apply it to the traveling salesman problem. You could alternatively use a modified greedy algorithm approach that starts at a random point and chooses the next location based on a random sided die based...

algorithm,graph,computer-science,graph-algorithm,shortest-path

Edited my answer based on counter example by David Eisenstat. The example you give in your question is not a good example of when Dijkstra will not work. I believe you can do this by modifying Dijkstra. The key is to keep track of multiple alternatives for each Vertex. Not...