简体   繁体   中英

How to find a word in a 2d grid?

This is the problem i was given to solve: Write a function searchDirection(word, row, col, direction, grid) that takes a word to find, a row and column starting position, a direction string such as "down", and a grid, and searches for the word in the given direction only, from the given starting position. If the word is found, a message is printed and True is returned. Otherwise, nothing is printed and False is returned.

I'm supposed to use nested for loops... but I don't know how to structure them?

Here are what the outputs should look like:

searchDirection("frog", 0, 5, "down", g) should print “frog found at (0, 5) going down” and return True

searchDirection("frog", 0, 5, "right", g) should return False, without printing anything

Here is a solution using a while loop, I will leave it as an exercise for you to figure out how to convert the logic into "nested for loops" (Hint: Take a look at the 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))

Output:

frog found at (0, 5) going down
True
False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM