word search

leetcode 第79题,图上的深搜题。
第一步,先要写个遍历循环,找到搜索的起点,也就是首字母。
第二步,从起点出发开始搜索,搜索时主要要记录已经走过的地方,这里可以使用一个二维的数组单独来记录,或者走过的地方标识为‘#’,搜索后恢复这个位置的字符。
注意,每次搜索时,都要比较word和当前路径已经遍历到的字符,这里可以使用增量式的比较方法,每次比较一个字符即可。

class Solution:
    def exist(self, board, word):
        """
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """
        row = len(board)
        col = len(board[0])

        def dfs(current_x, current_y, board, index, word):

            if index == len(word)-1:
                return True
            tmp = board[current_x][current_y]
            board[current_x][current_y] = '#'
            if current_x+1 < row and board[current_x+1][current_y] == word[index+1]:
                if dfs(current_x+1, current_y, board, index+1, word):
                    return True
            if current_x-1 >= 0 and board[current_x-1][current_y] == word[index+1]:
                if dfs(current_x-1, current_y, board, index+1, word):
                    return True
            if current_y+1 < col and board[current_x][current_y+1] == word[index+1]:
                if dfs(current_x, current_y+1, board, index+1, word):
                    return True 
            if current_y-1 >= 0 and board[current_x][current_y-1] == word[index+1]:
                if dfs(current_x, current_y-1, board, index+1, word):
                    return True
            board[current_x][current_y] = tmp

            return False

        for i in range(row):
            for j in range(col):
                if board[i][j] == word[0]:
                    if dfs(i, j, board, 0, word):
                        return True
        return False
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值