2018阿里筆試題一道
八卦陣相傳是由諸葛亮創設的一種戰鬥隊形和兵力部署,由八種陣勢組成。為了方便,採用矩陣來描述一個八卦陣,它由八個單陣組成,每個單陣由多個兵力區域組成形成一種陣勢,如下圖所示,其中數字為一個兵力區域的士兵個數。假設單陣與單陣之間兵力區域不會相鄰,且單陣中每個兵力區域至少存在一個相鄰兵力區域(注:相鄰是指在其左上,正上,右上,右方,右下,正下,左下,左方與其相鄰),請用最快的速度計算出八個單陣中的兵力(士兵個數)的最大值和最小值。
輸入:
輸入描述,例如:
第一行輸入是八陣圖的行數。
第二行輸入是八陣圖的列數。
後續行輸入每個區域兵力。每一行的資料中間使用空格分開,當前一行輸入完成後回車輸入下一行資料。
輸出:
輸出描述,例如:
輸出八個單陣中兵力最大值和最小值。
輸入範例:
20
20
34 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 0 0 0 30
0 23 10 5 5 0 0 0 5 5 5 5 5 0 0 0 30 0 40 0
0 9 0 0 5 0 0 0 4 4 4 4 4 0 0 0 0 30 0 0
0 8 7 7 0 5 0 0 3 3 3 3 0 0 0 0 7 0 9 0
0 9 0 0 5 0 5 0 0 12 12 0 0 0 0 10 0 0 0 9
0 0 0 0 5 0 0 5 0 12 12 0 0 5 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 12 12 0 0 5 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0 0
40 30 3 6 6 0 0 0 0 0 0 0 0 5 5 0 0 0 10 0
0 0 20 0 0 6 6 0 0 0 0 0 0 0 5 6 5 10 10 0
40 30 3 7 6 0 0 0 0 0 0 0 0 0 0 6 0 0 10 0
0 0 0 0 0 0 0 17 0 0 0 0 17 0 0 6 5 7 7 0
0 0 0 0 0 0 0 0 7 0 0 7 0 0 0 0 0 0 0 0
0 20 0 0 7 0 0 0 0 4 4 0 0 0 0 0 10 0 0 0
0 20 0 0 7 0 0 0 0 4 4 0 0 0 0 0 10 0 0 0
0 20 0 0 7 0 0 0 0 4 4 0 0 0 0 0 10 0 0 0
0 30 0 7 0 0 0 0 0 5 5 0 0 0 0 0 0 10 0 50
0 40 7 0 0 0 0 0 0 5 5 0 0 0 0 0 0 0 50 0
43 30 25 10 50 0 0 0 6 6 6 6 0 0 0 0 0 50 0 0
輸出範例:
323
116
主要採用回溯演算法,但是不知道為什麼通過率只有20%,可能阿里的題確實太難了。不過這是第一次做出阿里的筆試題,例題跑通了感覺很開心。程式碼如下,Python寫的:
n = int(raw_input()) m = int(raw_input()) a = [] bingli = [] zhuangtai = [[0 for x in range(m)] for y in range(n)] for i in range(n): a.append(list(map(int, raw_input().strip().split()))) def fangzhen(a, i, j): global在下剛剛入門演算法,萌新一枚,大家一起共勉。希望大佬不吝賜教。count count += a[i][j] if i+1 <= 19 and j <= 19 and a[i+1][j] != 0 and zhuangtai[i+1][j] == 0: zhuangtai[i + 1][j] = 1 fangzhen(a, i+1, j) if i <= 19 and j+1 <= 19 and a[i][j+1] != 0 and zhuangtai[i][j+1] == 0: zhuangtai[i][j + 1] = 1 fangzhen(a, i, j+1) ifi+1 <= 19 and j+1 <= 19 and a[i+1][j+1] != 0 and zhuangtai[i+1][j+1] == 0: zhuangtai[i + 1][j + 1] = 1 fangzhen(a, i+1, j+1) if i-1 >= 0 and j >= 0 and a[i-1][j] != 0 and zhuangtai[i-1][j] == 0: zhuangtai[i - 1][j] = 1 fangzhen(a, i-1, j) if i >= 0 and j-1 >= 0 and a[i][j-1] != 0 and zhuangtai[i][j-1] == 0: zhuangtai[i][j - 1] = 1 fangzhen(a, i, j-1) if i-1 >= 0 and j-1 >= 0 and a[i-1][j-1] != 0 and zhuangtai[i-1][j-1] == 0: zhuangtai[i - 1][j - 1] = 1 fangzhen(a, i-1, j-1) if i+1 <= 19 and j-1 >= 0 and a[i+1][j-1] != 0 and zhuangtai[i+1][j-1] == 0: zhuangtai[i + 1][j - 1] = 1 fangzhen(a, i+1, j-1) if i-1 >= 0 and j+1 <= 19 and a[i-1][j+1] != 0 and zhuangtai[i-1][j+1] == 0: zhuangtai[i - 1][j + 1] = 1 fangzhen(a, i-1, j+1) return count for i in range(n): for j in range(m): if a[i][j] != 0 and zhuangtai[i][j] == 0: zhuangtai[i][j] = 1 global count count = 0 fangzhen(a, i, j) bingli.append(count) bingli_max = max(bingli) bingli_min = min(bingli) print(bingli_max) print(bingli_min)