示例#1
0
def incidence_matrix_to_list(incimatrix):
    """
    Convert from an incidence matrix to adjacency lists.
    :param incimatrix: Input incidence matrix[nodeindex][edgeindex]
    :param edgemap: dictionary{(edge):edgeindex}
    :return: adjacent linked list
    """
    nodenum = len(incimatrix)
    edgenum = len(incimatrix[0])
    # # switch map to index:tuple
    # reversemap = {}
    # for key, value in edgemap.items():
    #     reversemap[value] = key
    lst = [SLL.LinkedList() for _ in range(nodenum)]
    for edge_index in range(edgenum):
        temppair = []
        for node_index in range(nodenum):
            if incimatrix[node_index][edge_index] == 1:
                temppair.append(node_index)
        lst[temppair[0]].append(temppair[1])
        lst[temppair[1]].append(temppair[0])
    # for node_index in range(nodenum):
    #     for edge_index in range(edgenum):
    #         if incimatrix[node_index][edge_index] == 1:
    #             edge = reversemap[edge_index]
    #             node = edge[0] if node_index != edge[0] else edge[1]
    #             lst[node_index].append(node)
    return lst
示例#2
0
def matrix_to_list(matrix):
    """
    Convert from an adjacency matrix to adjacency lists
    :param matrix: Input adjacency matrix[][]
    :return: Output a list of linked list, each linked list store the neighbours
    """
    length = len(matrix)
    lst = [SLL.LinkedList() for _ in range(length)]
    for i in range(length):
        for j in range(length):
            if matrix[i][j] == 1:
                lst[i].append(j)
    return lst