Leetcode: Word Search

本文介绍了一种使用深度优先搜索(DFS)算法在二维网格中查找指定单词的方法。通过创建一个辅助函数来验证路径的合法性,并利用一个visit数组记录已访问过的单元格,避免重复访问。该方法的时间复杂度为O(m²*n²)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Get idea from Code Ganker′s (优快云) solution, also from this solution


Question

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.

For example,
Given board =

[
[“ABCE”],
[“SFCS”],
[“ADEE”]
]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
Hide Tags Array Backtracking


Analysis

Treat each letter as a node in graph and its four cells as its neighbors. Use DFS to find path. Since the same cell may not be used more than once, we can create an array named visited to store info whether this cell have been visited.

Step:
1. look for all cells that can be the first one of word
2. for each cell, do DFS. Note that we need to set it be False at the end.

Complexity:
for init point, we look for all nodes, which takes O(m*n). For each DFS, it is O(E+V) = O(m*n+4m*n) = O(m*n). Thus it takes O( m2n2 ) totally.


Solution

class Solution:
    # @param {character[][]} board
    # @param {string} word
    # @return {boolean}
    def exist(self, board, word):
        if len(board)==0 or len(word)==0:
            return False

        self.move = [[0,0,1,-1],[1,-1,0,0]]        
        visited = [ [False]*len(board[0]) for dummy_i in range(len(board)) ]

        for i in range(len(board)):
            for j in range(len(board[0])):
                if self.search(board,word,0,i,j,visited):
                    return True
        return False

    def search(self,board,word,index,i,j,visited):
        if index==len(word):
            return True

        if i<0 or j<0 or i>=len(board) or j>=len(board[0]) 
             or word[index]!=board[i][j] or visited[i][j]==True:
            return False

        result = False
        visited[i][j] = True
        for direct in range(4):
            result = result or self.search(board, word, index+1, i+self.move[0][direct], 
                      j+self.move[1][direct],visited)
        visited[i][j] = False

        return result

Take-home message

The tricks here are:
1. to make logic clear, put all (or some) checks in helper function. In help function(search), it checks whether the indexes are in the board, whether it is visited …….
2. to create move array for moving, not need to list all directions one by one self.move = [[0,0,1,-1],[1,-1,0,0]]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值