File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change @@ -302,6 +302,61 @@ func generateMatrix(n int) [][]int {
302
302
}
303
303
```
304
304
305
+ Swift:
306
+
307
+ ``` swift
308
+ func generateMatrix (_ n : Int ) -> [[Int ]] {
309
+ var result = [[Int ]](repeating : [Int ](repeating : 0 , count : n), count : n)
310
+
311
+ var startRow = 0
312
+ var startColumn = 0
313
+ var loopCount = n / 2
314
+ let mid = n / 2
315
+ var count = 1
316
+ var offset = 1
317
+ var row: Int
318
+ var column: Int
319
+
320
+ while loopCount > 0 {
321
+ row = startRow
322
+ column = startColumn
323
+
324
+ for c in column ..< startColumn + n - offset {
325
+ result[startRow][c] = count
326
+ count += 1
327
+ column += 1
328
+ }
329
+
330
+ for r in row ..< startRow + n - offset {
331
+ result[r][column] = count
332
+ count += 1
333
+ row += 1
334
+ }
335
+
336
+ for _ in startColumn ..< column {
337
+ result[row][column] = count
338
+ count += 1
339
+ column -= 1
340
+ }
341
+
342
+ for _ in startRow ..< row {
343
+ result[row][column] = count
344
+ count += 1
345
+ row -= 1
346
+ }
347
+
348
+ startRow += 1
349
+ startColumn += 1
350
+ offset += 2
351
+ loopCount -= 1
352
+ }
353
+
354
+ if (n % 2 ) != 0 {
355
+ result[mid][mid] = count
356
+ }
357
+ return result
358
+ }
359
+ ```
305
360
306
361
307
362
You can’t perform that action at this time.
0 commit comments