Word Search
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Constraints:
board
andword
consists only of lowercase and uppercase English letters.1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
Example 1
1 | board = |
解题思路
回溯法。尝试从每个位置开始,合成单词。每个位置有上下左右四个选择,若当前选择无法合成单词,做下一个选择。若当前选择合成单词成功,直接返回。
复杂度分析
- 时间复杂度:$O(nm^4)$,总共有
n
个位置,单词的长度为m
。每个字母最多要经过四次选择。 - 空间复杂度:$O(m)$,用于存储单词合成的中间结果。
代码
1 | class Solution { |