0

I need some help concerning my code. After iterating through the numpy array I get a dictionary where you can see which element is connected to whom. The BFS method sorts out and put it in a visited list. I need to figure out how to put the keys into the queue. There's one start element. But not all of the keys, just the keys which are connected to each other. As you can see there are two areas of figures in the array.

import numpy as np

def graph():
    a = np.array([
        [0,  0,  0,  0,  0,  0,  0,  0,  0],
        [0,  0, 16, 12, 21,  0,  0,  0,  0],
        [0, 16,  0,  0, 17, 20,  0,  0,  0],
        [0, 12,  0,  0, 28,  0, 31,  0,  0],
        [0, 21, 17, 28,  0, 18, 19, 23,  0],
        [0,  0, 20,  0, 18,  0,  0, 11,  0],
        [0,  0,  0, 31, 19,  0,  0, 27,  0],
        [0,  0,  0,  0, 23, 11, 27,  0,  0],
        [0,  0,  0,  0,  0,  0,  0,  0,  0]],
        )

    graph = {}

    for r in range(len(a)):

        for c in range(len(a)

            if a[r, c] > 0:
                d = [r-1, c+1, r+1, c-1]

                if a[d[0], c] > 0 or a[r, d[1]] or a[d[2], c] or a[r, d[3]]:
                    graph[a[r, c]] = []
                    if a[d[0], c] > 0:
                        graph[a[r, c]].append(a[d[0], c])
                    if a[r, d[1]] > 0:
                        graph[a[r, c]].append(a[r, d[1]])
                    if a[d[2], c] > 0:
                        graph[a[r, c]].append(a[d[2], c])
                    if a[r, d[3]] > 0:
                        graph[a[r, c]].append(a[r, d[3]])
return(graph)

def bfs(graph, start):

queue = [start]
visited = [start]

while queue:

    for neighbour in graph.keys():

        if neighbour in queue:
            visited.append(graph[neighbour])
            queue.pop(0)

result = 0
print(queue)
print(visited)

bfs(graph(), 16)
DrBwts
  • 3,470
  • 6
  • 38
  • 62
  • For iterative access to elements, working with a list of lists will be more efficient than working an array. – hpaulj May 24 '20 at 18:38

1 Answers1

0

I modified the bfs method, see below. Basically the updated code traverses the graph by layer, using a double-ended queue that provides more efficiency for FIFO.

from collections import deque
def bfs(graph, start):
    deq = deque([start])
    visited = [start]
    while deq:
        for _ in range(len(deq)):
            node = deq.popleft()
            for neighbour in graph[node]:
                if neighbour not in visited:
                    visited.append(neighbour)
                    deq.append(neighbour)
    print(visited)

Output: [16, 12, 21, 17, 28, 20]

Kun Hu
  • 417
  • 5
  • 11