-1

这是我要解决的问题:编写一个函数 searchDirection(word, row, col, direction, grid),它需要一个词来查找,一个行和列的起始位置,一个方向字符串,如“down”,和一个网格,并从给定的起始位置仅在给定方向上搜索单词。如果找到该单词,则会打印一条消息并返回 True。否则,不打印任何内容并返回 False。

我应该使用嵌套的 for 循环......但我不知道如何构造它们?

以下是输出的样子:

searchDirection("frog", 0, 5, "down", g) 应该打印“frog found at (0, 5) going down”并返回 True

searchDirection("frog", 0, 5, "right", g) 应该返回 False,不打印任何内容

4

1 回答 1

0

这是一个使用 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
于 2020-11-12T04:43:34.020 回答