单词搜索
Word Search
题目详情
问题:单词搜索
考察:数组、字符串、递归、图
来源:Citadel
链接:https://www.jointaro.com/interviews/questions/word-search/
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" Output: true
Example 2:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" Output: true
Example 3:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" Output: false
Constraints:
m == board.lengthn = board[i].length1 <= m, n <= 61 <= word.length <= 15boardandwordconsists of only lowercase and uppercase English letters.
Follow up: Could you use search pruning to make your solution faster with a larger board?
解析
思路:从每个与首字母匹配的格子开始 DFS,向四个方向匹配下一个字符。搜索路径上临时标记已访问格子,回溯时恢复。
复杂度:最坏 O(mn * 4^L),空间 O(L)。