From 28552d7f5f0b356fe931f31682a03151862a9b51 Mon Sep 17 00:00:00 2001 From: Lanre Adedara Date: Thu, 23 May 2024 09:05:23 +0100 Subject: [PATCH] Swift Implementation for LCOF 29 --- .../README.md" | 34 +++++++++++++++++++ .../Solution.swift" | 29 ++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 "lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.swift" diff --git "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/README.md" "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/README.md" index c91788e2f795f..040e1a3354cd4 100644 --- "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/README.md" +++ "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/README.md" @@ -326,6 +326,40 @@ public class Solution { } ``` +#### Swift + +```swift +class Solution { + func spiralOrder(_ matrix: [[Int]]) -> [Int] { + guard !matrix.isEmpty && !matrix[0].isEmpty else { + return [] + } + + let m = matrix.count + let n = matrix[0].count + var vis = Array(repeating: Array(repeating: false, count: n), count: m) + var ans = [Int]() + var i = 0, j = 0, k = 0 + let dirs = [0, 1, 0, -1, 0] + + for _ in 0..= m || y >= n || vis[x][y] { + k = (k + 1) % 4 + x = i + dirs[k] + y = j + dirs[k + 1] + } + i = x + j = y + } + + return ans + } +} +``` + diff --git "a/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.swift" "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.swift" new file mode 100644 index 0000000000000..75c18c41817ad --- /dev/null +++ "b/lcof/\351\235\242\350\257\225\351\242\23029. \351\241\272\346\227\266\351\222\210\346\211\223\345\215\260\347\237\251\351\230\265/Solution.swift" @@ -0,0 +1,29 @@ +class Solution { + func spiralOrder(_ matrix: [[Int]]) -> [Int] { + guard !matrix.isEmpty && !matrix[0].isEmpty else { + return [] + } + + let m = matrix.count + let n = matrix[0].count + var vis = Array(repeating: Array(repeating: false, count: n), count: m) + var ans = [Int]() + var i = 0, j = 0, k = 0 + let dirs = [0, 1, 0, -1, 0] + + for _ in 0..= m || y >= n || vis[x][y] { + k = (k + 1) % 4 + x = i + dirs[k] + y = j + dirs[k + 1] + } + i = x + j = y + } + + return ans + } +} \ No newline at end of file