classSolution{ funcgenerateMatrix(_n: Int) -> [[Int]] { var matrix = [[Int]].init(repeating: [Int].init(repeating: 0, count: n), count: n) var left =0, right = n -1, top =0, bottom = n -1 var num =1 while left <= right && top <= bottom { for col in left ... right { matrix[top][col] = num num +=1 } if (top +1<= bottom) { for row in (top+1) ... bottom { matrix[row][right] = num num +=1 } }
if left < right && top < bottom { for col instride(from: right-1, to: left, by: -1) { matrix[bottom][col] = num num +=1 }
for row instride(from: bottom, to: top, by: -1) { matrix[row][left] = num num +=1 } } left +=1 right -=1 top +=1 bottom -=1 } return matrix } }