问题描述
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:
1 | Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" |
1 | Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" |
1 | Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" |
Constraints:
- m == board.length
- n = board[i].length
- 1 <= m, n <= 6
- 1 <= word.length <= 15
- board and word consists of only lowercase and uppercase English letters.
解题思路
dfs深度搜索,不断的回溯递归
注意结束条件
index >= word.length || i < 0 || j < 0 || i >= m || j >= n
和str.length == word.length
注意标记已经访问过的元素,防止重复,同时一轮dfs后记得复原
代码如下:
JavaScript
1 | /** |
- 时间复杂度:O(mnword.length)
- 空间复杂度:O(1)