Skip to content

Instantly share code, notes, and snippets.

@charlieInDen
Created December 12, 2020 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlieInDen/87e9239ba42c4530ffb9642a713611da to your computer and use it in GitHub Desktop.
Save charlieInDen/87e9239ba42c4530ffb9642a713611da to your computer and use it in GitHub Desktop.
func spiral(_ matrix: [[Int]]) -> [Int] {
/// Base condition
var result = [Int]()
guard matrix.isEmpty == false else { return result }
/// Logic
var r1 = 0, c1 = 0
var r2 = matrix.count - 1, c2 = matrix[0].count - 1
while r1 <= r2 && c1 <= c2 {
/// Go from c1 to c2 and append the element
for c in stride(from: c1, through: c2, by: 1) {
result.append(matrix[r1][c])
}
/// Go from next row till endof row
for r in stride(from: r1 + 1, through: r2, by: 1) {
result.append(matrix[r][c2])
}
if r1 < r2 && c1 < c2 {
/// Move from c2-1 till c1
for c in stride(from: c2 - 1, through: c1, by: -1) {
result.append(matrix[r2][c])
}
/// Move from r2-1 till r1
for r in stride(from: r2 - 1, to: r1, by: -1) {
result.append(matrix[r][c1])
}
}
r1 = r1 + 1
r2 = r2 - 1
c1 = c1 + 1
c2 = c2 - 1
}
return result
}
//let input = [[1,2,3,4],
// [5,6,7,8],
// [9,10,11,12],
// [13,14,15,16]]
let input = [[1,2,3],
[4,5,6],
[7,8,9]]
let output = spiral(input)
print(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment