问题
给定一个整数 n,生成一个方阵,填充为 元素从 1 到 n^2 按螺旋顺序排列。例如,给定 n = 3,
您应该返回以下矩阵:[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5] ]
class Solution
{
func generateMatrix(n: Int) -> [[Int]]
{
var matrix =
[[Int]](count: n, repeatedValue: [Int](count: n, repeatedValue: 0))
var left = 0
var top = 0
var right = n - 1
var down = n - 1
var count = 1
while left <= right && top < down // shouble left <= right && top <= down
{
for j in (left...right)
{
matrix[top][j] = count
count += 1
}
top += 1
for i in (top...down)
{
matrix[i][right] = count
count += 1
}
right -= 1
for j in (left...right).reverse()
{
matrix[down][j] = count
count += 1
}
down -= 1
for i in (top...down).reverse()
{
matrix[i][left] = count
count += 1
}
left += 1
}
return matrix
}
}
var test = Solution()
var result = test.generateMatrix(3)
print(result)
这是我的结果,[ [ 1, 2, 3 ], [ 8, 0, 4 ], [ 7, 6, 5 ] ],9是 丢失的。我想我应该将 while 循环更改为“left <= right && top <= down",but I got an error.
这个错误让我很困惑。由于在“左<= right && top <= down", variable top has no chance to get over variable down, however, the error alerts me range end < start.
”的条件下非常感谢您的帮助!非常感谢您的宝贵时间。
看起来像作业,但我会咬。假设
i, j
是从0, 0
开始的行索引和列索引,则螺旋运动可以描述如下:
j
直到到达右侧的矩阵边界i
直到到达底部的矩阵边界j
直到到达左侧的矩阵边界i
直到到达顶部的矩阵边界这是代码:
let n = 3
// Init an all-zero matrix
var 矩阵 = 数组(重复:数组(重复:0,计数:n),计数:n)
var i = 0
var j = 0
// These 2 variables control how we move the i and j cursors
// Initial move is from left to right
var deltaI = 0
var deltaJ = 1
for number in 1...(n*n) {
matrix[i][j] = number
let nextI = i + deltaI
let nextJ = j + deltaJ
// nextCellIsEmpty == true if:
// * nextI is within boundary of the matrix; and
// * nextJ is within boundary of the matrix; and
// * matrix[nextI][nextJ] is not taken
let nextCellIsEmpty = (0..<n ~= nextI) && (0..<n ~= nextJ) && (matrix[nextI][nextJ] == 0)
// If the next cell is not empty, we need to adjust how
// the cursors move
if !nextCellIsEmpty {
if deltaJ == 1 { deltaI = 1; deltaJ = 0; }
else if deltaI == 1 { deltaI = 0; deltaJ = -1; }
else if deltaJ == -1 { deltaI = -1; deltaJ = 0; }
else if deltaI == -1 { deltaI = 0; deltaJ = 1; }
}
i += deltaI
j += deltaJ
}
matrix.forEach { print($0) }
~=
是“模式匹配”运算符。如果 a..<b ~= c
,则
a <= c < b
返回 true
最后添加这段代码:
矩阵[(下+上)/ 2][(左+右)/ 2] = n * n
因为你的算法,中心的矩阵无法满足你的限制,
所以只需添加此代码即可。
此外,n应该是满足你的算法的奇数(1,3,5...),应该考虑。