如果我理解正确的话,这是一个解决方案 . 说实话,这是一个非常有趣的问题 . :d
我们的想法是创建一个给定边长的框,然后围绕网格移动此框并记录它的顶点 . 请参阅以下内容:
# Assuming the grid is always a square grid.
grid.size
# The matrix of row indices.
rindex.grid
nrow=grid.size, ncol=grid.size, byrow=TRUE)
# We can traverse the grid by moving any given square either right or down in any
# single move. We choose to go right.
move.square.right
new.square
}
# Going right, capture co-ordinates of all squares in this row.
collect.sq.of.edge.length.in.row.number
rownum=1) {
first.square.in.row
first.square.in.row
first.square.in.row + grid.size * (elength - 1))
squares.in.row
FUN=move.square.right,
this.square=first.square.in.row))
squares.in.row
}
# Now we start going down the columns and using the function above to collect
# squares in each row. The we will rbind the list of squares in each row into a
# dataframe. So what we get is a (grid.size - (elength - 1) ^ 2) x 4 matrix where
# each row is the co-ordinates of a square of edge length elength.
collect.sq.of.edge.length.in.grid
all.squares=lapply(X=seq_len(grid.size - (elength - 1)),
FUN=collect.sq.of.edge.length.in.row.number,
grid.size=grid.size, elength=elength)
all.squares
all.squares
}
这似乎表明我们为所有边长获得了正确数量的方框:
tmp
sapply(tt, nrow)
[1] 400 361 324 289 256 225 196 169 144 121 100 81 64 49 36 25 16 9 4 1
此外,它适用于您的3x3示例:
collect.sq.of.edge.length.in.grid(grid.size=3, elength=2)
[,1] [,2] [,3] [,4]
[1,] 1 2 4 5
[2,] 2 3 5 6
[3,] 4 5 7 8
[4,] 5 6 8 9