Created
January 10, 2021 01:28
-
-
Save tanveer/1c819a2316fd0084a356f5116a4c32e8 to your computer and use it in GitHub Desktop.
Revisions
-
tanveer created this gist
Jan 10, 2021 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,65 @@ 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 }