即使纯粹把所有的情况列出来也只占20多行啊。def count_neighbours(grid, row, col):
if (row < 0 or row >= len(grid)) and (col < 0 or col >= len(grid[0])):
return 0
elif (row > 0 and row < len(grid)-1) and (col > 0 and col < len(grid[0])-1) :#in the middle
return grid[row-1][col-1] + grid[row-1][col] + grid[row-1][col+1] + grid[row][col-1] + grid[row][col+1] + grid[row+1][col-1] + grid[row+1][col] + grid[row+1][col+1]
elif row == 0 and col == 0:# in four corners
return grid[row][col+1] + grid[row+1][col+1] + grid[row+1][col]
elif row == 0 and col == len(grid[0])-1 :
return grid[row][col-1] + grid[row+1][col-1] + grid[row+1][col]
elif row == len(grid)-1 and col == 0 :
return grid[row-1][col] + grid[row-1][col+1] + grid[row][col+1]
elif row == len(grid)-1 and col == len(grid[0])-1:
return grid[row-1][col] + grid[row][col-1] + grid[row-1][col-1]
elif row == 0 and (col > 0 and col < len(grid[0])-1): #on four sides
return grid[row][col-1] + grid[row][col+1] + grid[row+1][col-1] + grid[row+1][col] + grid[row+1][col+1]
elif row == len(grid) -1 and (col > 0 and col < len(grid[0])-1):
return grid[row][col-1] + grid[row][col+1] + grid[row-1][col-1] + grid[row-1][col] + grid[row-1][col+1]
elif (row > 0 or row < len(grid)-1) and col == 0:
return grid[row-1][col] + grid[row+1][col] + grid[row-1][col+1] + grid[row][col+1] + grid[row+1][col+1]
elif (row > 0 or row < len(grid)-1) and col == len(grid[0])-1:
return grid[row-1][col] + grid[row+1][col] + grid[row-1][col-1] + grid[row][col-1] + grid[row+1][col-1]
else:
return 0
其实在Checkio上面有人用4行就解决了这个问题,那个人真的好厉害啊:def count_neighbours(grid, row, col):
rows = range(max(0, row - 1), min(row + 2, len(grid)))
cols = range(max(0, col - 1), min(col + 2, len(grid[0])))
return sum(grid[r][c] for r in rows for c in cols) - grid[row][col]
|