Word Search

Problem

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:

复制代码
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

Example 2:

复制代码
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true

Example 3:

复制代码
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false

Intuition

The problem involves determining whether a given word exists in the provided grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. Additionally, the same letter cell may not be used more than once. This problem can be solved using a depth-first search (DFS) approach.

Approach

DFS Function:

Implement a DFS function (dfs) that takes three parameters: the current row r, the current column c, and the index i representing the position in the word.

In the base case:

If i is equal to the length of the word, return True (the word has been found).

If the current cell (r, c) is out of bounds or has already been visited or contains a letter different from the corresponding letter in the word, return False.

Mark the current cell as visited by adding (r, c) to the set path.

Recursively call the dfs function for adjacent cells in all four directions (up, down, left, right) with the updated index i.

After the recursive calls, remove (r, c) from the set path to backtrack.

Iterate Over Grid:

Iterate over each cell in the grid and call the dfs function for each cell with the starting index i set to 0.

If the dfs function returns True for any cell, the word exists in the grid, and the function can return True.

Return Result:

If no cell results in a True return from the dfs function, return False, indicating that the word does not exist in the grid.

Complexity

  • Time complexity:

The time complexity is O(M * N * 4^L), where M is the number of rows, N is the number of columns, and L is the length of the word. The factor of 4^L accounts for the branching factor of the DFS.

  • Space complexity:

The space complexity is O(L), where L is the length of the word. This is due to the space required for the recursion stack and the set path used to track visited cells.

Code

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        rows, cols = len(board), len(board[0])
        path = set()

        def dfs(r, c, i):
            if i == len(word):
                return True
            if (r < 0 or c < 0 or
                r >= rows or c >= cols or
                word[i] != board[r][c] or (r, c) in path):
                return False

            path.add((r, c))
            res = (dfs(r + 1, c, i + 1) or
                    dfs(r - 1, c, i + 1) or
                    dfs(r, c - 1, i + 1) or
                    dfs(r, c + 1, i + 1))
                
            path.remove((r, c))
            return res

        for r in range(rows):
            for c in range(cols):
                if dfs(r, c, 0): return True
        return False
相关推荐
卑微小文1 分钟前
企业级IP代理安全防护:数据泄露风险的5个关键防御点
前端·后端·算法
Erik_LinX26 分钟前
算法日记36:leetcode095最长公共子序列(线性DP)
算法
2301_7665360527 分钟前
刷leetcode hot100--动态规划3.11
算法·leetcode·动态规划
VT.馒头27 分钟前
【力扣】2629. 复合函数——函数组合
前端·javascript·算法·leetcode
DOMINICHZL38 分钟前
卡尔曼滤波算法从理论到实践:在STM32中的嵌入式实现
stm32·嵌入式硬件·算法
CodeJourney.1 小时前
光储直流微电网:能源转型的关键力量
数据库·人工智能·算法·能源
GUOYUGRA1 小时前
高纯氢能源在线监测分析系统组成和作用
人工智能·算法·机器学习
Chenyu_3101 小时前
05.基于 TCP 的远程计算器:从协议设计到高并发实现
linux·网络·c++·vscode·网络协议·tcp/ip·算法
论迹2 小时前
【二分算法】-- 三种二分模板总结
java·开发语言·算法·leetcode
衡玖2 小时前
c语言闯算法--排序
c语言·数据结构·算法