leetcode: 回溯 79. 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.

思路

用回溯。由于一次只取board中的一个字符进行比较,因此不用复制 board ,而是直接修改board值(表示这个cell被用过了),如果走不通,再将修改的值复原。

def existSub(self,board,word,i,j):
        if len(word) == 0:
            return True
        
        c = word[0:1]
        temp = board[i][j]
        board[i][j] = ""
        
        option_i = [-1,1]
        if i == 0:
            option_i.remove(-1)
        if i==len(board)-1:
            option_i.remove(1)
        option_j = [-1,1]
        if j == 0:
            option_j.remove(-1)
        if j == len(board[0])-1:
            option_j.remove(1)

        for k in option_i:
            if c == board[i+k][j]:
                if self.existSub(board,word[1:],i+k,j):
                    return True
        for k in option_j:
            if c == board[i][j+k]:
                if self.existSub(board,word[1:],i,j+k):
                    return True
        
        board[i][j] = temp
        return False
            
    
    def exist(self, board: List[List[str]], word: str) -> bool:
        if len(board)==0:
            return False
        
        c_start = word[0:1]
        m,n = len(board),len(board[0])
        for i in range(m):
            for j in range(n):
                if board[i][j] == c_start:
                    if self.existSub(board,word[1:],i,j):
                        return True
        return False
发布了45 篇原创文章 · 获赞 1 · 访问量 3359

猜你喜欢

转载自blog.csdn.net/qq_22498427/article/details/104568461