简体   繁体   中英

DFS/BFS Implementation: Directed Graph

While attempting to display all nodes in a directed graph, incorrect nodes are displayed!

What is it, that I am doing wrong here? Also, how can I use the graph dictionary instead of defining all edges, is there a way to use use the dictionary?

Expected Results:

1  --> Node(s): ['2', '4']
2  --> Node(s): ['3', '5', '7']
3  --> Node(s): ['1', '6']
4  --> Node(s): ['6']
5  --> Node(s): ['7', '8']
6  --> Node(s): ['8']
7  --> Node(s): ['8', '9']
8  --> Node(s): ['9']

Actual Results:

1  --> Node(s): [2, 3, 4]
2  --> Node(s): [1, 3, 5, 7]
3  --> Node(s): [1, 2, 6]
4  --> Node(s): [1, 6]
5  --> Node(s): [2, 7, 8]
6  --> Node(s): [3, 4, 8]
7  --> Node(s): [2, 5, 8, 9]
8  --> Node(s): [5, 6, 7, 9]
9  --> Node(s): [7, 8]

If using the graph dictionary as:

graph = {'1': ['2','4'], '2': ['3', '5', '7'], '3': ['1','6'], '4': ['6'], 
         '5': ['7','8'], '6': ['8'], '7': ['8', '9'], '8': ['9']}

Code:

n_nodes = {}

# Search for all nodes and create an empty array for each node
def add_nodes(node_array):
    for node in node_array:
        if node not in n_nodes:
            n_nodes[node] = []

def add_edge(edge):
    u, v = edge
    if (v not in n_nodes[u]) and (u not in n_nodes[v]):
        n_nodes[u].append(v)
        if (u != v):
            n_nodes[v].append(u)

add_nodes([i+1 for i in range(9)])

add_edge((1,2))
add_edge((1,4))
add_edge((2,3))
add_edge((2,5))
add_edge((2,7))
add_edge((3,1))
add_edge((3,6))
add_edge((4,6))
add_edge((5,7))
add_edge((5,8))
add_edge((6,8))
add_edge((7,8))
add_edge((7,9))
add_edge((8,9))

# Print All Nodes
for key in sorted(n_nodes):
    print (key, " --> Node(s):",sorted(n_nodes[key]))

Your code is treating edges as undirected edges: they are always added in both directions. So just remove the code that adds the edge in the opposite direction.

Change this:

if (v not in n_nodes[u]) and (u not in n_nodes[v]):
    n_nodes[u].append(v)
    if (u != v):
        n_nodes[v].append(u)

...to:

if v not in n_nodes[u]:
    n_nodes[u].append(v)

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