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

这篇博客分享了2018年阿里巴巴算法工程师实习笔试中的一道题目,解题策略侧重于使用广度优先搜索(BFS)。在搜索过程中,每个节点的所有相邻节点会被加入到列表中,为了避免重复处理,已访问过的节点不再记录。
摘要由CSDN通过智能技术生成


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

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值