[LeetCode] 79. Word Search

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

题目

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.

思路

总体就是递归遍历。
但有两个点需要注意:
1.遍历的时候,需要放置回溯。做法的技巧在于 原值修改,然后 递归,最后原值复原。
2.可能 board 与 word 都是一个值所以, if p == len(word): 与 if px == -1 or py == -1: 的位置需要注意

code

def get_up(px, py, board):
    if px - 1 >= 0:
        return px-1, py
    return -1, -1


def get_down(px, py, board):
    if px + 1 < len(board):
        return px +1, py
    return -1, -1


def get_left(px, py, board):
    if py - 1 >= 0:
        return px , py -1
    return -1, -1


def get_right(px, py, board):
    if py + 1 < len(board[0]):
        return px , py + 1
    return -1, -1


def is_word(px, py, p, board, word):
    if p == len(word):
        return True

    if px == -1 or py == -1:
        return False
    # print(p,px,py)
    if word[p] != board[px][py]:
        return False
    tmpchar = board[px][py]
    board[px][py] = '-1'
    bl_flag = is_word(get_up(px, py, board)[0], get_up(px, py, board)[1], p + 1, board, word) or is_word(
        get_down(px, py, board)[0], get_down(px, py, board)[1], p + 1, board, word) or is_word(
        get_left(px, py, board)[0], get_left(px, py, board)[1], p + 1, board, word) or is_word(
        get_right(px, py, board)[0], get_right(px, py, board)[1], p + 1, board, word)
    board[px][py] = tmpchar
    return bl_flag
class Solution:

    def exist(self, board, word):
        """
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """
        for i in range(len(board)):
            for j in range(len(board[0])):
                if is_word(i, j, 0, board, word):
                    return True
        return False
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值