返回
算法探索:单词搜索的迷宫奥秘
前端
2023-12-24 06:49:44
在计算机科学领域,单词搜索问题颇具挑战性,它考验着算法的灵活性与严谨性。在本文中,我们将深入探讨单词搜索的奥秘,并以回溯算法为利器,征服迷宫般的文字方格。
首先,让我们对单词搜索问题进行定义:给定一个包含字母的二维网格和一个目标单词,判断该单词是否出现在网格中。目标单词可以以任意方向(水平、垂直、对角线)出现,但不能跳过相邻的字母。
回溯算法是一种递归算法,它通过逐步探索所有可能的解决方案来解决问题。在单词搜索问题中,回溯算法可以从网格中的任意位置开始,逐个字母地探索目标单词。当字母匹配时,算法继续探索下一个字母;当字母不匹配或超出网格边界时,算法返回并尝试从其他位置重新开始。
def word_search(grid, word):
"""
Searches for a word in a 2D grid.
Args:
grid: A 2D grid of letters.
word: The word to search for.
Returns:
True if the word is found in the grid, False otherwise.
"""
# Check if the word is empty.
if not word:
return True
# Check if the grid is empty.
if not grid:
return False
# Check if the word is longer than the grid.
if len(word) > len(grid) * len(grid[0]):
return False
# Create a set of visited cells.
visited = set()
# Iterate over all cells in the grid.
for row in range(len(grid)):
for col in range(len(grid[0])):
# If the current cell is the start of the word,
# start a new search.
if grid[row][col] == word[0]:
if _word_search_helper(grid, word, row, col, visited):
return True
# If the word was not found, return False.
return False
def _word_search_helper(grid, word, row, col, visited):
"""
Helper function for word_search.
Args:
grid: A 2D grid of letters.
word: The word to search for.
row: The current row.
col: The current column.
visited: A set of visited cells.
Returns:
True if the word is found in the grid, False otherwise.
"""
# Check if the word is empty.
if not word:
return True
# Check if the current cell is out of bounds.
if row < 0 or row >= len(grid) or col < 0 or col >= len(grid[0]):
return False
# Check if the current cell has been visited.
if (row, col) in visited:
return False
# Check if the current cell matches the first letter of the word.
if grid[row][col] != word[0]:
return False
# Mark the current cell as visited.
visited.add((row, col))
# Recursively search for the rest of the word.
if _word_search_helper(grid, word[1:], row + 1, col, visited) or \
_word_search_helper(grid, word[1:], row - 1, col, visited) or \
_word_search_helper(grid, word[1:], row, col + 1, visited) or \
_word_search_helper(grid, word[1:], row, col - 1, visited):
return True
# Unmark the current cell as visited.
visited.remove((row, col))
# If the word was not found, return False.
return False
回溯算法的运用恰到好处,它实现了单词搜索问题的有效求解。同时,我们在代码中使用了简洁明了的注释,以帮助读者轻松理解算法的运作过程。
希望这篇文章能够帮助您更深入地理解单词搜索问题和回溯算法。如果您有其他问题,欢迎随时提出!