标签:color class lis backtrack str img exist alt 字符
回溯法
思路:
创建一个二维数组mark用来记录用过的位置,先遍历数组找到和单词第一个字母相同的元素,在mark中标记此元素,从此元素开始进行回溯,看上下左右是否能找到单词第二个字符,如果能找到,mark中标记对应位置,继续进行回溯,直到找到单词所有字符为止,如果没有找到,则返回False。
代码:
class Solution: def exist(self, board: List[List[str]], word: str) -> bool: def backtrack(i,j,subWord): if len(subWord) == 0: return True for direct in directions: cur_i = i + direct[0] cur_j = j + direct[1] if 0<= cur_i <r and 0<= cur_j<c and board[cur_i][cur_j] == subWord[0]: if mark[cur_i][cur_j]==0: continue mark[cur_i][cur_j]=0 if backtrack(cur_i,cur_j,subWord[1:])==True: return True else: mark[cur_i][cur_j]=1 return False r = len(board) if r == 0: return False directions = [(0,1),(0,-1),(1,0),(-1,0)] c = len(board[0]) mark = [[1 for _ in range(c)] for _ in range(r)] for i in range(r): for j in range(c): if board[i][j] == word[0]: mark[i][j]=0 if backtrack(i,j,word[1:]) == True: return True else: mark[i][j] = 1 return False
标签:color class lis backtrack str img exist alt 字符
原文地址:https://www.cnblogs.com/nilhxzcode/p/13124478.html