COMP9021-Quiz8

题目:

Randomly fills a grid of size 10 x 10 with 0s and 1s, in an estimated proportion of 1/2 for each, and computes the longest leftmost path that starts from the top left corner -- a path consisting of horizontally or vertically adjacent 1s --, visiting every point on the path once only.


题目大意:

输入一个整数,随机生成一个10*10的0,1网格。然后从左上角找最左边最长的路径。如果左上角的数字是0,则没有路径。


COMP9021-Quiz8_第1张图片
输出示意图

思路:

刚看到此题首先想到的是BFS,但是要控制好方向。这里需要理解好最左边是什么意思。由于是从左上角出发,又要走向最左,因此我们应当往东(E)方向走。如果东方向走不通则往南(S)走。

假设我们往东部走则我们此时是面向东部的,因为要找最左边的路径,因此我们应当往我们的左手边走,即应当往北部(N)走。如果左手边走不通就往咱们的正面走即继续往东(E)走,如果该方向依然走不通则往咱们的右手边走,即南部方向(S)。从西、南、北方向过来也是顺着这个思路找接下来的方向。这是本题的一个难点也困扰了我很长时间,解决该问题的窍门在于不要看图中所示的方向,应当模拟咱们自己在图中走,从一个方向过来的时候以咱们自己为基准查找左、前、右的方向,最后在转化到图中。

此外,还应该对路径的长度进行一个比较,因为此题除了找最左的还需要找最长的路径。


代码:

from random import seed, randrange
import queue
import numpy as np

def display_grid():
    for i in range(len(grid)):
        print('   ', ' '.join(str(grid[i][j]) for j in range(len(grid[0]))))

def leftmost_longest_path_from_top_left_corner():
    '''
    Find the leftmost longest path
    :return:
    '''
    if grid[0][0] == 1:
        result = [[(0, 0)]]
    else:
        return None
    length1 = len(grid)
    length2 = len(grid[0])

    #('W', 'E', 'S', 'N')
    q = queue.Queue()
    directions = {'E': (0, 1), 'S': (1, 0), 'W': (0, -1), 'N': (-1, 0)}
    adirs = {' ': ('E', 'S'),
             'E': ('N', 'E', 'S'),
             'S': ('E', 'S', 'W'),
             'W': ('S', 'W', 'N'),
             'N': ('W', 'N', 'E')}

    q.put((' ', (0, 0), [(0, 0)]))
    while not q.empty():
        node = q.get()
        dir = node[0]
        list1 = node[2]
        x = node[1][0]
        y = node[1][1]
        for ref in adirs[dir]:
            x1 = x + directions[ref][0]
            y1 = y + directions[ref][1]
            if x1 >= 0 and x1 < length2 and y1 >= 0 and y1 < length1:
                if grid[x1][y1] == 1 and not list1.__contains__((x1, y1)):
                    list2 = list1.copy()
                    list2.append((x1, y1))
                    if len(list2) > len(result[0]):
                        result.clear()
                    result.append(list2.copy())
                    q.put((ref, (x1, y1), list2))
    return result[0]

provided_input = input('Enter one integer: ')
try:
    for_seed = int(provided_input)
except ValueError:
    print('Incorrect input, giving up.')
seed(for_seed)
grid = [[randrange(2) for _ in range(10)] for _ in range(10)]
print('Here is the grid that has been generated:')
display_grid()
path = leftmost_longest_path_from_top_left_corner()
if not path:
    print('There is no path from the top left corner.')
else:
    print(f'The leftmost longest path from the top left corner is: {path}')

你可能感兴趣的:(COMP9021-Quiz8)