Problem
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 | board = |
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
Analysis
这道题目要求的是单词字母的连接,采用的是DFS。以二维矩阵中的每一个字母开头,往四个方向寻找,每个方向都做DFS。然后记录在word
上的下标,这样就能判断是否遍历完整个单词了。
Solution
需要用一个和原矩阵同样大小的visited
矩阵去记录哪些位置的字母已经被遍历过了。每个方向遍历的时候,记得遍历完之后要把当前的位置的visited
重新设置为false
。
Code
1 | class Solution { |
Summary
这道题目的基本思路就是二维矩阵的DFS,往四个方向遍历,难度并不是特别很大,关键要记录好字符串的idx。希望这篇博客能够帮助到您,感谢您的支持,欢迎转发、分享、评论,谢谢!