如何在二维网格中查找单词?

How to find a word in a 2d grid?

这是我要解决的问题: 编写一个函数 searchDirection(word, row, col, direction, grid) ,它接受一个要查找的词、行和列的起始位置、方向字符串(例如“向下”)和一个网格,并在给定的范围内搜索词仅方向,从给定的起始位置。如果找到该词,将打印一条消息并 returned 为 True。否则,不会打印任何内容,并且 returned.

为 False

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

输出应如下所示:

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

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

这是一个使用 while 循环的解决方案,我将把它留作练习,让您弄清楚如何将逻辑转换为“嵌套 for 循环”(提示:看一下 More Control Flow Tools section of the official documentation):

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