Member-only story
Rotating a matrix
Solving LeetCode 48. Rotate Image,
4 min readNov 10, 2019
Here is a tutorial that can help you for a tricky little problem from LeetCode, and the solution in Swift. Have fun!
Prerequisites:
- Some programming experience
Difficulty: Easy | Normal | Challenging
The problem
We rotate the following matrix:
Which becomes the following:
Method 1: Simple rotation
Rotate the corners
The index of the corners can be derived from the size of the matrix. Here we describe the position as a coordinate, and then the derivation in Swift (where size = matrix.count).
top left = [0,0] = matrix[0][0]
top right = [0,3–1] = matrix[0][size — 1]
bottom right = [3–1, 3–1] = matrix[size-1][size-1]