问题
给定整数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&lt; = right&amp;&amp; 顶部&lt; = down“,但我收到了错误。
这个错误让我很困惑。因为在条件“left&lt; = 正确的&amp;&amp; top&lt; = down“,变量top没有机会克服变量 但是,错误警告我范围结束&lt;启动。
非常感谢你的帮助!真的很感激你的时间。
答案 0 :(得分:0)
看起来像家庭作业,但我会咬人。假设i, j
是从0, 0
开始的行和列索引,螺旋运动可以描述如下:
j
,直到您点击右侧的矩阵边界i
,直至到达底部的矩阵边界j
,直到您点击左侧的矩阵边界i
,直至到达顶部的矩阵边界以下是代码:
let n = 3
// Init an all-zero matrix
var matrix = Array(0..<n).map { _ in [Int](count: n, repeatedValue: 0) }
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) }
~=
是&#34;模式匹配&#34;运营商。如果a..<b ~= c
a <= c < b
会返回true
答案 1 :(得分:0)
最后添加此代码:
矩阵[(底部+顶部)/ 2] [(左+右)/ 2] = n * n
由于你的算法,中心的矩阵不能满足你的限制,
所以只需添加此代码即可。
此外,n应该是奇数(1,3,5 ......),可以满足你的算法,应该考虑。