from random import randint graph = { 0: [1, 7], 1: [0, 2], 2: [1, 3, 4], 3: [2], 4: [2], 5: [6], 6: [7, 5], 7: [0, 8, 6], 8: [7], } visited = [] ci = randint(0, 9) c = graph[ci] print("Walk starts from node", ci) moves = 0 path = [] while True: if ci not in visited: visited.append(ci) print("Found node:", ci) path.append(ci) ci = graph[ci][randint(0, len(graph[ci])-1)] moves += 1 if len(visited) == len(graph): break print("Graph explored in", moves, "steps")