Reputation: 63
I'm looking for an algorithm to find all cycles with a total weight of all its edges that is greater than 0. I heard that this problem is NP-complete, but since I want to solve this for a special graph that always looks more or less the same, I hope there is an easier method.
My graph looks like this:
It always is a square of n * n
vertices and edges between all horizontally and vertically adjacent vertices. There are just two possible weights, for black edges -1 and for the green ones its +1.
For this example the cycles I'm looking for would be:
What would be an efficient algorithm for this task? It should be quite fast, because I also want to do this for graphs with n = 25 => 625
vertices.
Upvotes: 2
Views: 337
Reputation: 618
Why not using a basic cycle detection with a DFS and some modifications to it :
The pseudo-code might look like this :
dfs(node, weight):
if state[node] is "in progress" AND weight > 0
// This is a cycle we want
Keep in memory the path (just go throught the cycle once more)
if state[node] is "visited"
Stop
state[node] = "in progress"
For each neighbour
dfs(neighbour, weight + edge_weight)
state[node] = "visited"
If you do that for each starting node, you should get a complexity in time of approximately O(N * M) with N the number of vertices and M the number of edges.
Hope this helps !
EDIT : forgot to update the state
Upvotes: 1