Description
Difficulty: Medium
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.
Example:
1
2
3
4
5
6
7
8
9
10 board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
Solution - 1: DFS Recursion
这道因为二维数组感觉和 Leetcode 130: Surrounded Regions 很像,也可以用递归函数解决。因为一个数只能用一次我们可以建立一个二维数组finished来表示这个位置上的数是否已经用过(用过:1,没用过:0)。
1 | class Solution { |
时间复杂度:O(3^k) 最差情况下,需要遍历矩阵中的所有相符长度的字符串。走过的位置无法回头,所有是3。
空间复杂度:O(n*m) 新建数组finished的维度为 nm,递归深度最坏情况下为 nm, 即k为mn
m,n 为矩阵的长宽,k为字符串word的长度。
其实还可以再把代码简化一些,比如
- 避免重复这里,可以不额外建finished,而是把走过的位置上的数设为特殊符号以标记,可以节省空间复杂度
- 把上下左右的搜查用||连接起来,节省很多代码行数,但是要先确认x,y的值有没有超出边界。
- 不用substring,而是把word直接转化成char array
1 | class Solution { |
Summary
- 思路都是一样的,感觉自己写出来的虽然对我而言是最好理解的,但代码还是不够简洁,有很多可以节省优化的地方。
总之希望自己能坚持下去,每周记录分享几道有趣的题和解法。也欢迎大家留言讨论补充(●’◡’●)