Search code examples
pythonpython-3.xadjacency-matrix

How can i determine all routes from one node to another by using adjacency matrix?


mat = [[0,1,1,0],[1,0,0,1],[1,0,0,1],[0,1,1,0]] 

network image

How can i determine route from adjacency matrix?

Thanks in advance for your interest..

Expected result: from 1 to 4:

1-2-4

1-3-4


Solution

  • You can use networkx for this.

    Example:

    >>> import networkx as nx
    >>> import numpy as np
    >>> g = nx.from_numpy_array(np.array(mat)) 
    >>> g = nx.relabel_nodes(g, {i:i+1 for i in range(len(mat))})
    >>> list(nx.all_simple_paths(g, 1, 4))
    [[1, 2, 4], [1, 3, 4]]