2018年阿里巴巴算法工程师实习笔试题目


解题思路:广度搜索。每搜索一个,要把他所有连接的点放进列表,为避免重复,该点不被记录

import numpy as np
w , l = input().split(' ')
w ,l  = int(w), int(l)
in_list = np.zeros(shape=[w,l])
for i in range(w):
    value = input().split(' ')
    for j in range(l):
        in_list[i][j] = int(value[j])        
queue,all_list = [],[]
def get_sum(in_list,i,j,m,n):
    queue,sum_list,in_list[i][j]=[[i,j]],in_list[i][j],0
    while queue:
        i, j = queue[0][0],queue[0][1]
        if i>0 and j>0 and in_list[i-1][j-1] != 0:#左上
            queue.append([i-1,j-1])
            sum_list = sum_list + in_list[i-1][j-1]
            in_list[i-1][j-1] = 0
        if i>0 and in_list[i-1][j] !=0:#上
            queue.append([i-1,j])
            sum_list = sum_list + in_list[i-1][j]
            in_list[i-1][j] = 0
        if i>0 and j+1<n  and in_list[i-1][j+1] !=0:#右上
            queue.append([i-1,j+1])
            sum_list = sum_list + in_list[i-1][j+1]
            in_list[i+1][j+1] = 0
        if  j+1<n and in_list[i][j+1] !=0:#右
            queue.append([i,j+1])
            sum_list = sum_list + in_list[i][j+1]
            in_list[i][j+1] = 0
        if i+1<m and j+1<n and in_list[i+1][j+1] !=0:#右下
            queue.append([i+1,j+1])
            sum_list = sum_list + in_list[i+1][j+1]
            in_list[i+1][j+1] = 0
        if i+1<m  and in_list[i+1][j] !=0: #下
            queue.append([i+1,j])
            sum_list = sum_list + in_list[i+1][j]
            in_list[i+1][j] = 0
        if i+1<m and j>0 and in_list[i+1][j-1] !=0:#左下
            queue.append([i+1,j-1])
            sum_list = sum_list + in_list[i+1][j-1]
            in_list[i+1][j-1] = 0
        if j>0 and in_list[i][j-1] !=0:#左
            queue.append([i,j-1])
            sum_list = sum_list + in_list[i][j-1]
            in_list[i][j-1] = 0
        del queue[0]
    return sum_list
def main():
    for i in range(w):
        for j in range(l):
            if in_list[i][j] !=0: all_list.append(get_sum(in_list,i,j,w,l))
    #print('所有值',all_list)
    all_list.sort()
    print('最小值',all_list[0])
    print('最大值',all_list[-1])
if __name__ == 'main':
    main()

猜你喜欢

转载自blog.csdn.net/qq_15264999/article/details/80307711