题目说明:
题解:暴力求解
<1>找到输入数组中的所有形状为3*3的数组
<2>判断每一个3*3形状数组是否是幻方
每个幻方有以下几点要求:
(1)每个元素在1-9之间
(2)每个元素各不相同
(3)各行之和相等
(4)各列之和相等
(5)两对角线之和相等
def numMagicSquaresInside(self, grid): rows = len(grid) cols = len(grid[0]) count = 0 res = [] row = 0 col = 0 while row+2<rows: map = {} flag2 = 0 for i in range(row,row+3): tmp = [] for j in range(col,col+3): tmp.append(grid[i][j]) if grid[i][j]>=1 and grid[i][j]<=9: flag2 = flag2+1 if grid[i][j] not in map: map[grid[i][j]] = 1 else: map[grid[i][j]] +=1 res.append(tmp) flag = 0 if len(map)==9: flag = flag+1 if sum(res[0])==sum(res[1]) and sum(res[1])==sum(res[2]): flag = flag+1 if sum(x[0] for x in res)==sum(y[1] for y in res) and sum(z[2] for z in res)==sum(x[0] for x in res): flag = flag+1 if sum(res[i][i] for i in range(3))==res[0][2]+res[1][1]+res[2][0]: flag = flag+1 if flag == 4 and flag2==9: count = count+1 if col+2<cols-1: col = col+1 res = [] else: col = 0 row = row+1 res = [] return count