简体   繁体   中英

Implementing Search in my java function

I need a java code that chooses the shortest path between two words with each step only changing one letter. I'd like to implement Depth-First Search; I think that would solve my problem. I was reading about it but I don't know how to implement it. Could anyone help me?

I overestimated some of the problem constraints in my comment; this is actually a very straightforward BFS problem. DFS is not appropriate because it follows each path all the way to a terminal node before exploring neighbors of nodes close to the root node. This means there is no guarantee of shortest path. On the other hand, BFS explores nearby nodes first and will guarantee a shortest path. This problem illustrates the difference between the two approaches very nicely.

Your current implementation is recursive, which uses the call stack as the DFS data structure. Since stacks are last-in-first-out (LIFO) structures, neighbors of the current node will be quickly buried underneath neighbors of those neighbors which are popped and explored first.

Here's an implementation of your find method as BFS using a queue (first-in-first-out or FIFO):

def find(start, target, words):
    alpha = [chr(x) for x in range(97, 123)]
    visited = {start: None}
    queue = [start]

    while queue:
        curr = queue.pop(0)

        if curr == target:
            path = []

            while curr:
                path.insert(0, curr)
                curr = visited[curr]

            return path

        letters = list(curr)

        for i, c in enumerate(letters):
            for letter in alpha:
                new_word = "".join(letters[:i]) + letter + "".join(letters[i+1:])

                if new_word in words and new_word not in visited:
                    visited[new_word] = curr
                    queue.append(new_word)


words = set([w.strip() for w in open("dictionary.txt").readlines()])
print(find("lead", "gold", words))
print(find("hide", "seek", words))

Output:

['lead', 'load', 'goad', 'gold']
['hide', 'bide', 'bids', 'beds', 'bees', 'sees', 'seek']

Note that the second path is equally short as your example but uses a different route. You could easily adjust the algorithm to calculate all shortest paths if desired.

In contrast, a simple modification of changing the queue to a stack (one character change: pop(0) -> pop() shows us the result of a DFS:

['lead', 'leas', 'leys', 'lays', 'laws', 'lawn', 'lain', 'lair', 'wair', 'wait', 'watt', 'wats', 'wars', 'wary', 'wavy', 'wave', 'wane', 'wand', 'wynd', 'wyns', 'wyes', 'woes', 'wows', 'yows', 'yowl', 'yawl', 'yawp', 'yaup', 'yaud', 'yard', 'yarn', 'tarn', 'tart', 'taut', 'taus', 'tavs', 'vavs', 'vans', 'vang', 'yang', 'yank', 'yack', 'yuck', 'yuch', 'yech', 'yeah', 'year', 'wear', 'wean', 'ween', 'weet', 'west', 'wost', 'wort', 'worn', 'sorn', 'sori', 'soli', 'sols', 'soys', 'soya', 'soma', 'some', 'sone', 'song', 'sung', 'suns', 'suss', 'sass', 'sash', 'wash', 'wasp', 'wisp', 'wiss', 'wigs', 'zigs', 'zits', 'ziti', 'titi', 'tipi', 'tips', 'tins', 'tiny', 'tidy', 'tide', 'tire', 'tiro', 'tyro', 'typo', 'type', 'tyne', 'tune', 'tuna', 'tufa', 'tuft', 'toft', 'tofu', 'tolu', 'toll', 'tool', 'toon', 'town', 'towy', 'tory', 'tors', 'tots', 'tote', 'toke', 'take', 'taka', 'taxa', 'taxi', 'tali', 'talk', 'task', 'tusk', 'tush', 'tosh', 'toph', 'soph', 'soth', 'sith', 'site', 'size', 'bize', 'bise', 'bisk', 'birk', 'birr', 'bier', 'beer', 'bees', 'bets', 'beth', 'bath', 'bate', 'bare', 'barm', 'balm', 'bals', 'bams', 'bums', 'bump', 'burp', 'bury', 'busy', 'bust', 'butt', 'bott', 'bota', 'bora', 'mora', 'more', 'move', 'rove', 'roue', 'roux', 'doux', 'dour', 'dorr', 'dorp', 'gorp', 'goop', 'goos', 'gods', 'gids', 'gies', 'gien', 'girn', 'girt', 'gist', 'gast', 'vast', 'vase', 'vale', 'vole', 'volt', 'molt', 'moly', 'mopy', 'mops', 'moss', 'mosk', 'monk', 'mono', 'mozo', 'bozo', 'bolo', 'bold', 'gold']
['hide', 'hive', 'hove', 'howe', 'hows', 'hoys', 'hoya', 'hora', 'horn', 'hern', 'hers', 'hets', 'heth', 'hath', 'hate', 'haze', 'hazy', 'mazy', 'many', 'mans', 'mays', 'mayo', 'mako', 'make', 'mare', 'mart', 'maut', 'maun', 'mawn', 'mown', 'moon', 'moot', 'mott', 'mots', 'moss', 'mosk', 'monk', 'mono', 'mozo', 'bozo', 'boyo', 'toyo', 'toro', 'tory', 'towy', 'cowy', 'cowl', 'cool', 'coos', 'cops', 'cope', 'cote', 'cute', 'cuts', 'cuss', 'cusk', 'cask', 'cast', 'cant', 'cane', 'cave', 'cavy', 'caky', 'laky', 'lakh', 'lash', 'lass', 'laws', 'yaws', 'yawp', 'yaup', 'yaud', 'yard', 'yarn', 'warn', 'wary', 'waly', 'wall', 'wawl', 'pawl', 'pail', 'pair', 'parr', 'pars', 'pats', 'paty', 'pity', 'pith', 'pish', 'piss', 'pips', 'pipe', 'pine', 'pint', 'punt', 'puny', 'pony', 'pons', 'poms', 'pomp', 'poop', 'poor', 'pour', 'pout', 'post', 'pose', 'pore', 'pork', 'pock', 'poco', 'polo', 'poll', 'pull', 'puls', 'pugs', 'pugh', 'vugh', 'vugg', 'mugg', 'migg', 'migs', 'mirs', 'miry', 'airy', 'airt', 'girt', 'giro', 'gyro', 'gyre', 'gybe', 'gibe', 'gibs', 'gins', 'gink', 'gunk', 'guck', 'geck', 'geek', 'seek']

As you can see, that wasn't the shortest path at all!

I think we are in the same class, with the same assignment. Just a heads up, be careful what you post online especially your codes as it could get detected by our lecturer and fail your assignment as it is a violation of academic policy, specifically plagiarism. :)

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