1. 程式人生 > 其它 >【leetcode】79. 單詞搜尋

【leetcode】79. 單詞搜尋

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        result = False
        directions = [(0,1), (0,-1), (-1,0), (1,0)]
        def next_in(i,j,k):            
            if k == wl-1 and board[i][j] == word[k]:
                return True

            result = False
            
for direction in directions: new_i = i + direction[0] new_j = j + direction[1] new_k = k + 1 if 0 <= new_i < rm and 0 <= new_j < rl: if board[new_i][new_j] == word[new_k]: if ((new_i,new_j) not
in locations): locations.add((i,j)) if next_in(new_i,new_j,new_k): return True else: locations.remove((i,j)) return
result k = 0 rm = len(board) rl = len(board[0]) wl = len(word) locations = set() for i in range(len(board)): for j in range(len(board[i])): if board[i][j] == word[k]: if next_in(i,j,k): return True return result