grid = [[1,2,2], [4,5,2], [7,8,2]] n = len(grid) table = {} for i in range(n): for j in range(n): if (i,j) not in table: table[(i,j)] = [] if 0 <= i+1 < n: table[(i,j)].append([(i+1,j),abs(grid[i+1][j] - grid[i][j])]) if 0 ...