人体矩阵转换成僵尸

时间:2016-07-20 04:47:13

标签: algorithm matrix

我在接受采访时面对这个问题。请让我知道这个任务的可能答案。

我们有一个像3 X 3,5 x 5或7 X 7的矩阵。在中间,我们在所有节点上都有X(代表僵尸)和0(无效或空白)或1(人类)。 X在一分钟内创建了所有相邻的人类节点僵尸。   那么创建所有矩阵僵尸需要多少时间。

1 个答案:

答案 0 :(得分:1)

不要让术语欺骗你:这是一个图形问题。我假设一个僵尸也可以到达对角线的人类。

如果您从“Zombie point”进行广度优先搜索,您将能够确定该时间(如果存在)。这基本上就是你如何继续:( Python中的代码示例)

matrix = [['1', '0', '0'],['1', 'X', '1'],['0', '0', '0']]
mid = len(matrix)//2
yet_to_explore = [(mid,mid,0)]
explored_set = {} # This is a hashset of explored nodes
while [] != yet_to_explore:
    cur_vertex = yet_to_explore.pop(0)
    x = cur_vertex[0]
    y = cur_vertex[1]
    if (x,y) in explored_set:
        continue
    explored_set[(x,y)] = cur_vertex[2]
    matrix[x][y] = 'X'
    for i in range(-1,2):
        if 0 > x + i or len(matrix) <= x + i:
            continue
        for j in range(-1,2):
            if 0 > y + j or len(matrix) <= y + j:
                continue
            elif 0 == i and 0 == j:
                continue
            elif matrix[x+i][y+j]=='1':
                yet_to_explore.append((x+i, y+j, cur_vertex[2]+1))
# If your matrix contains a '1' after the BFS this means some human were not reachable (they are isolated) -> the desired time does not exist since not every human can be a zombie
# Else the time you are looking for is the following result:
time = max(list(explored_set.values()))

存在幸存者的例子:

matrix = [['0', '0', '0', '0', '0', '0', '0'],
          ['1', '1', '1', '1', '0', '0', '0'], # The human on the left will be contamined within 4 min
          ['0', '0', '0', '1', '0', '0', '0'],
          ['1', '0', '0', 'X', '0', '0', '0'], # The human on the left will survive
          ['0', '0', '1', '0', '1', '0', '0'],
          ['0', '0', '1', '0', '0', '1', '0'],
          ['0', '1', '0', '0', '0', '0', '1']] # The human on the right will be contamined within 3 min

寻找假想的幸存者只是一种练习。