79. Word Search

https://leetcode.com/problems/word-search/description/

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:

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.

Constraints:

  • board and word consists only of lowercase and uppercase English letters.

  • 1 <= board.length <= 200

  • 1 <= board[i].length <= 200

  • 1 <= word.length <= 10^3

Thoughts

矩阵中是否出现了给定单词,一个字符只能计入一次。依次遍历矩阵中所有可能的路径=> DFS。配合标记防止走回头路。

Code

Analysis

时间复杂度参照m_rao的分析" I think the time complexity is (mn_4^k) where k is the length of the string; mn for for loop and for the dfs method its 4^k. Since the dfs method goes only as deep as the word length we have T(k)=4(T(k-1))=4_4T(k-2)=....=.. which will be 4^k."

Last updated

Was this helpful?