150强访谈简单

单词搜索

“单词搜索”问题的详细指南和 Python 实现。

问题陈述

简单

给定一个 m x n 字符板网格和一个字符串单词,如果单词存在于网格中,则返回 true。

该单词可以由顺序相邻的单元格的字母构成,其中相邻的单元格水平或垂直相邻。同一字母单元不得使用多次。

实现函数 exist(board: list, word: str) -> bool

约束条件
  • 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

示例

Example 1
Input
[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCCED"
Output
True
Explanation

The word ABCCED can be traced: A(0,0)->B(0,1)->C(0,2)->C(1,2)->E(2,2)->D(2,1).

Example 2
Input
[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "SEE"
Output
True
Explanation

The word SEE can be traced: S(1,3)->E(2,3)->E(2,2).

Example 3
Input
[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCB"
Output
False
Explanation

Cannot trace ABCB without reusing cells.

Need a Hint?
考虑使用回溯特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。