这是一个使用 while 循环的解决方案,我将把它留作练习,让您了解如何将逻辑转换为“嵌套 for 循环”(提示:查看官方文档的更多控制流工具部分) :
def searchDirection(word, row, col, direction, grid):
m = len(grid)
if not m:
return False
n = len(grid[0])
if not n:
return False
directions = {
"up": (-1, 0),
"right": (0, 1),
"down": (1, 0),
"left": (0, -1)
}
if direction not in directions:
return False
i = 0
r, c = row, col
while i < len(word) and 0 <= r < m and 0 <= c < n:
if grid[r][c] != word[i]:
return False
r += directions[direction][0]
c += directions[direction][1]
i += 1
if i == len(word):
print(f"{word} found at ({row}, {col}) going {direction}")
return i == len(word)
g = [['a', 'b', 'c', 'd', 'e', 'f'],
['a', 'b', 'c', 'd', 'e', 'r'],
['a', 'b', 'c', 'd', 'e', 'o'],
['a', 'b', 'c', 'd', 'e', 'g'],
['a', 'b', 'c', 'd', 'e', 'f'],
['a', 'b', 'c', 'd', 'e', 'f']]
print(searchDirection("frog", 0, 5, "down", g))
print(searchDirection("frog", 0, 5, "right", g))
输出:
frog found at (0, 5) going down
True
False