Sunday 15 May 2011

algorithm - How to traverse through a adjacency matrix? -


An adjacency matrix presents a connection between the nodes in an arbitrary tree.

Here's the excitation matrix that presents an unfiltered graph:

 1 2 3 4 1 0 1 1 0 2 1 0 1 0 3 1 1 0 0 0 0 0 0 < / Pre> 

This matrix presents a graph where nodes 1 and 2 are connected, 1 and 3 are connected, 2 and 3 are connected.

How to do all the combinations of possible path in this type of graph using such matrix? I mean choosing a node 1 is a different combination, then say, 1-2 is a different combination 1-2-3; 3-1-2

So how to brush all the combinations using these rules?

I like C #, C ++, or Java language samples)

Given the constraints of your example, it does not take any more than 40 lines of code.

Basically you are currently inspecting one to visit one connected nodes. There is no new node to support tracking after you detect it.

In addition to this, you will need some methods to keep track of the path that is traveling for the current node. In the example, I keep this information on the stack to keep it safe from some memory management headache.

  #include & lt; Stdio.h & gt; #define N_NODES 4 # Define NAME_OFFSET 1 int edges [N_NODES] [N_NODES] = {{0, 1, 1, 0}, {1, 0, 1,}, {1, 1, 0,}, {0, 0, 0}}; Int visited [N_NODES] = {0, 0, 0}; Structure node {int node; Struct node * prev; }; Zero Travel (Int node, Structure node * prev_node) {Structure node n = {node, pre_node}; Structure node * p = & amp; N; Printf ("% d% s", p-> node + NAME_OFFSET, (p-> gt; prev! = NULL)? "- & gt;": "\ n"); While ((p = p-> behind)! = Null); Visited [node] 1 =; Int i; For (i = 0; i & lt; N_NODES; ++ i) if (visited (i [i] == 0) & amp; (edge ​​[node] [i] == 1)) (i , & Amp; n); Visited [node] = 0; } Int main (int argc, char * argv []) {int i; For (i = 0; i & lt; N_NODES; ++ i) {Visit (i, NULL); } Return 0; }   

Product:

  1 2-> 1 3-> 2- & gt; 1 3 - & gt; 1 2-> 3-> 1 2-> 2 3-> 1-> 2 3-> 2 1- & gt; 3-> 2 3-1-> 3 2- & gt; 1-> 3 2- & gt; 3 1- & gt; 2- & gt; 3 4   

I think what you wanted.

No comments:

Post a Comment