I have a somewhat complicated question. I am provided a list of words (each word has the same length). I am given two words into my function (StartNode and EndNode) and my task is to find the shortest path between the two (A follow-up would be how to collect all paths from startNode to EndNode). The words can only be connected if they have at most a 1 word difference. For example, TRIE and TREE could be connected since they only differ by one letter (I v E) but TRIE and TWEP can't be connected since they have 2 character differences.
My solution was to first build an adjacency list, which I successfully implemented, and then compute a BFS to determine whether a path exists between the startNode and endNode. I am able to determine if a path exists but I'm unsure on how I can keep track of the path.
My attempt is as follows:
def shortestPath(startNode, endNode, words):
adjList=createGraph(words)
print(adjList)
#Returns shortest path from startNode to EndNode
visited=set()
q=collections.deque()
total=-1
q.append(startNode)
while q:
node=q.popleft()
visited.add(node)
if node==endNode:
if node!=startNode:
return total+1
total=total+1
for i in adjList[node]:
if i not in visited:
print(i)
q.append(i)
return -1
My BFS doesn't take in the path and the total_length is quite obviously wrong too. Is there any way I can improve my algorithm?
Sample Input:
{'POON': ['POIN', 'LOON'], 'PLEE': ['PLEA', 'PLIE'], 'SAME': [], 'POIE': ['PLIE', 'POIN'], 'PLEA': ['PLEE', 'PLIE'], 'PLIE': ['PLEE', 'POIE', 'PLEA'], 'POIN': ['POON', 'POIE'], 'LOON': ['POON']}
startWord: POON
endWord: PLEA
Expected Output:
POON -> POIN -> POIE -> PLIE -> PLEA
Current Output:
POIN
LOON
POIE
PLIE
PLEE
PLEA
PLEA
6
Any tips on where I am going wrong?