Created
January 10, 2021 01:28
-
-
Save tanveer/1c819a2316fd0084a356f5116a4c32e8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| func generateMatrix(_ n: Int) -> [[Int]] { | |
| var maxRow = n | |
| var maxCol = n | |
| var startRow = 0 | |
| var startCol = 0 | |
| let currRow = 0 | |
| let currCol = 0 | |
| var direction = "R" | |
| var valueCounter = 1 | |
| var result = [[Int]](repeating: [Int](repeating: 0, count: n), count: n) | |
| while currRow < n && currCol < n && valueCounter < n * n + 1 { | |
| if direction == "R" { | |
| for currCol in startCol..<maxCol { | |
| if result[currRow][currCol] == 0 { | |
| result[currRow][currCol] = valueCounter | |
| valueCounter += 1 | |
| } | |
| } | |
| startRow += 1 | |
| direction = "D" | |
| } | |
| if direction == "D" { | |
| for row in startRow..<maxRow { | |
| if result[row][currCol] == 0 { | |
| result[row][currCol] = valueCounter | |
| valueCounter += 1 | |
| } | |
| } | |
| maxCol -= 1 | |
| direction = "L" | |
| } | |
| if direction == "U" { | |
| for row in stride(from: maxRow, through: startRow, by: -1) { | |
| if result[row][currCol] == 0 { | |
| result[row][currCol] = valueCounter | |
| valueCounter += 1 | |
| } | |
| } | |
| startCol += 1 | |
| direction = "R" | |
| } | |
| if direction == "L" { | |
| for col in stride(from: maxCol, through: startCol, by: -1) { | |
| if result[currRow][col] == 0 { | |
| result[currRow][col] = valueCounter | |
| valueCounter += 1 | |
| } | |
| } | |
| maxRow -= 1 | |
| direction = "U" | |
| } | |
| } | |
| return result | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment