简体   繁体   中英

Python Implementing array as tree then implementing BFS

I'm unsure how to implement the following problem. I have a 2D array that I need to turn into a tree where the value of each node is determined from the matrix, but I'm not sure how to implement the method of correctly creating the appropriate tree. Here's an example for clarification:

    Matrix:


 0[ 3.  1.]
 1[ 6.  4.]
 2[ 2.  0.]
 3[ 5.  3.]
 4[ 1.  6.]
 5[ 4.  2.]
 6[ 0.  5.]
 7[ 3.  1.]`

Using that matrix I would then create a tree where the children of any given node is determined by the numbers in it's row of the matrix. For example if I chose 7 to be the root, I would get:

           7
        3     1
      5  3   6  4

And would continue to build the tree until a zero is reached. Where I would then return the path to the 0. (The matrix can have more than 2 columns, generating more than 2 children per node)

I'm having trouble determining what the code to implement the tree generation would be, it seems like it would be some variation of breadth-first, but I'm unsure.

I think the confusion stems from you asking about building a tree - that's not necessary, since you already have the graph structured . You have the links between each element in your matrix, and since it really isn't a tree (there are loops where a child can point to a parent if it were a tree) - it's already a graph.

Then it becomes a matter of applying a regular BFS and keeping track of the path for each step in your path while exploring:

# graph
m = {
    0: (3, 1),
    1: (6, 4),
    2: (2, 0),
    3: (5, 3),
    4: (1, 6),
    5: (4, 2),
    6: (0, 5),
    7: (3, 1),
}

# seed queue
queue = [(7, [])]

# bfs
while (queue):
    idx, path = queue.pop(0)
    path.append(idx)

    for n_idx in m[idx]:
        # check if the next node would be a 0
        if not n_idx:
            print(path)
            queue = []
            break

        # append the next index and a copy of the current path object    
        queue.append((n_idx, list(path)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM